home *** CD-ROM | disk | FTP | other *** search
/ Languguage OS 2 / Languguage OS II Version 10-94 (Knowledge Media)(1994).ISO / gnu / calc202a.lha / calc-2.02a / calc.el < prev    next >
Lisp/Scheme  |  1993-06-01  |  113KB  |  3,496 lines

  1. ;; Calculator for GNU Emacs, part I
  2. ;; Copyright (C) 1990, 1991, 1992, 1993 Free Software Foundation, Inc.
  3. ;; Written by Dave Gillespie, daveg@synaptics.com.
  4.  
  5. ;; This file is part of GNU Emacs.
  6.  
  7. ;; GNU Emacs is distributed in the hope that it will be useful,
  8. ;; but WITHOUT ANY WARRANTY.  No author or distributor
  9. ;; accepts responsibility to anyone for the consequences of using it
  10. ;; or for whether it serves any particular purpose or works at all,
  11. ;; unless he says so in writing.  Refer to the GNU Emacs General Public
  12. ;; License for full details.
  13.  
  14. ;; Everyone is granted permission to copy, modify and redistribute
  15. ;; GNU Emacs, but only under the conditions described in the
  16. ;; GNU Emacs General Public License.   A copy of this license is
  17. ;; supposed to have been given to you along with GNU Emacs so you
  18. ;; can know your rights and responsibilities.  It should be in a
  19. ;; file named COPYING.  Among other things, the copyright notice
  20. ;; and this notice must be preserved on all copies.
  21.  
  22.  
  23.  
  24. ;;; Calc is split into many files.  This file is the main entry point.
  25. ;;; This file includes autoload commands for various other basic Calc
  26. ;;; facilities.  The more advanced features are based in calc-ext, which
  27. ;;; in turn contains autoloads for the rest of the Calc files.  This
  28. ;;; odd set of interactions is designed to make Calc's loading time
  29. ;;; be as short as possible when only simple calculations are needed.
  30.  
  31. ;;; Suggested usage:
  32. ;;;
  33. ;;;   (autoload 'calc-dispatch "calc" "Emacs Calculator" t nil)
  34. ;;;   (global-set-key "\e#" 'calc-dispatch)
  35. ;;;   Type `M-# M-#' to start.
  36. ;;;
  37. ;;; The Calc home directory must be added to the Emacs load-path:
  38. ;;; 
  39. ;;;   (setq load-path (cons "/x/y/z/calc" load-path))
  40. ;;;
  41. ;;; where "/x/y/z/calc" represents the full name of the Calc home directory.
  42. ;;;
  43. ;;; See the file INSTALL for a complete list of recommeded autoload
  44. ;;; commands (though only calc-dispatch is absolutely necessary).
  45.  
  46.  
  47. ;;; Author's address:
  48. ;;;   Dave Gillespie, daveg@synaptics.com, uunet!synaptx!daveg.
  49. ;;;   Synaptics, Inc., 2698 Orchard Parkway, San Jose, CA 95134.
  50. ;;;
  51. ;;; The old address daveg@csvax.cs.caltech.edu will continue to
  52. ;;; work for the foreseeable future.
  53. ;;;
  54. ;;; The latest version of Calc is always available from anonymous FTP
  55. ;;; on csvax.cs.caltech.edu [131.215.131.131]; look in ~ftp/pub/calc*.
  56. ;;; It should also be available on prep.ai.mit.edu.
  57. ;;;
  58. ;;; Bug reports and suggestions are always welcome!
  59.  
  60.  
  61. ;;; All functions, macros, and Lisp variables defined here begin with one
  62. ;;; of the prefixes "math", "Math", or "calc", with the exceptions of
  63. ;;; "full-calc", "full-calc-keypad", "another-calc", "quick-calc",
  64. ;;; "report-calc-bug", and "defmath".  User-accessible variables begin
  65. ;;; with "var-".
  66.  
  67.  
  68.  
  69. (provide 'calc)
  70.  
  71.  
  72. (defun calc-record-compilation-date ()
  73.   (calc-record-compilation-date-macro)
  74. )
  75. (calc-record-compilation-date)
  76.  
  77.  
  78. ;;; The "###autoload" comment will be used by Emacs version 19 for
  79. ;;; maintaining the loaddefs.el file automatically.
  80.  
  81. ;;;###autoload
  82. (defvar calc-info-filename "calc.info"
  83.   "*File name in which to look for the Calculator's Info documentation.")
  84.  
  85. ;;;###autoload
  86. (defvar calc-settings-file "~/.emacs"
  87.   "*File in which to record permanent settings; default is \"~/.emacs\".")
  88.  
  89. ;;;###autoload
  90. (defvar calc-autoload-directory nil
  91.   "Name of directory from which additional \".elc\" files for Calc should be
  92. loaded.  Should include a trailing \"/\".
  93. If nil, use original installation directory.
  94. This can safely be nil as long as the Calc files are on the load-path.")
  95.  
  96. ;;;###autoload
  97. (defvar calc-gnuplot-name "gnuplot"
  98.   "*Name of GNUPLOT program, for calc-graph features.")
  99.  
  100. ;;;###autoload
  101. (defvar calc-gnuplot-plot-command nil
  102.   "*Name of command for displaying GNUPLOT output; %s = file name to print.")
  103.  
  104. ;;;###autoload
  105. (defvar calc-gnuplot-print-command "lp %s"
  106.   "*Name of command for printing GNUPLOT output; %s = file name to print.")
  107.  
  108.  
  109. ;; Address of the author of Calc, for use by report-calc-bug.
  110. (defvar calc-bug-address "daveg@synaptics.com")
  111.  
  112.  
  113. ;; If T, scan keymaps to find all DEL-like keys.
  114. ;; If NIL, only DEL itself is mapped to calc-pop.
  115. (defvar calc-scan-for-dels t)
  116.  
  117.  
  118.  
  119. (defvar calc-extensions-loaded nil)
  120.  
  121.  
  122.  
  123. ;;; IDEAS:
  124. ;;;
  125. ;;;   Fix rewrite mechanism to do less gratuitous rearrangement of terms.
  126. ;;;   Implement a pattern-based "refers" predicate.
  127. ;;;
  128. ;;;   Make it possible to Undo a selection command.
  129. ;;;   Figure out how to allow selecting rows of matrices.
  130. ;;;   If cursor was in selection before, move it after j n, j p, j L, etc.
  131. ;;;   Consider reimplementing calc-delete-selection using rewrites.
  132. ;;;
  133. ;;;   Implement line-breaking in non-flat compositions (is this desirable?).
  134. ;;;   Implement matrix formatting with multi-line components.
  135. ;;;
  136. ;;;   Have "Z R" define a user command based on a set of rewrite rules.
  137. ;;;   Support "incf" and "decf" in defmath definitions.
  138. ;;;   Have defmath generate calls to calc-binary-op or calc-unary-op.
  139. ;;;   Make some way to define algebraic functions using keyboard macros.
  140. ;;;
  141. ;;;   Allow calc-word-size=0 => Common Lisp-style signed bitwise arithmetic.
  142. ;;;   Consider digamma function (and thus arb. prec. Euler's gamma constant).
  143. ;;;   May as well make continued-fractions stuff available to the user.
  144. ;;;
  145. ;;;   How about matrix eigenvalues, SVD, pseudo-inverse, etc.?
  146. ;;;   Should cache matrix inverses as well as decompositions.
  147. ;;;   If dividing by a non-square matrix, use least-squares automatically.
  148. ;;;   Consider supporting matrix exponentials.
  149. ;;;
  150. ;;;   Have ninteg detect and work around singularities at the endpoints.
  151. ;;;   Use an adaptive subdivision algorithm for ninteg.
  152. ;;;   Provide nsum and nprod to go along with ninteg.
  153. ;;;
  154. ;;;   Handle TeX-mode parsing of \matrix{ ... } where ... contains braces.
  155. ;;;   Support AmS-TeX's \{d,t,}frac, \{d,t,}binom notations.
  156. ;;;   Format and parse sums and products in Eqn and Math modes.
  157. ;;;
  158. ;;;   Get math-read-big-expr to read sums, products, etc.
  159. ;;;   Change calc-grab-region to use math-read-big-expr.
  160. ;;;   Have a way to define functions using := in Embedded Mode.
  161. ;;;
  162. ;;;   Support polar plotting with GNUPLOT.
  163. ;;;   Make a calc-graph-histogram function.
  164. ;;;
  165. ;;;   Replace hokey formulas for complex functions with formulas designed
  166. ;;;      to minimize roundoff while maintaining the proper branch cuts.
  167. ;;;   Test accuracy of advanced math functions over whole complex plane.
  168. ;;;   Extend Bessel functions to provide arbitrary precision.
  169. ;;;   Extend advanced math functions to handle error forms and intervals.
  170. ;;;   Provide a better implementation for math-sin-cos-raw.
  171. ;;;   Provide a better implementation for math-hypot.
  172. ;;;   Provide a better implementation for math-make-frac.
  173. ;;;   Provide a better implementation for calcFunc-prfac.
  174. ;;;   Provide a better implementation for calcFunc-factor.
  175. ;;;
  176. ;;;   Provide more examples in the tutorial section of the manual.
  177. ;;;   Cover in the tutorial:  simplification modes, declarations,
  178. ;;;       bitwise stuff, selections, matrix mapping, financial functions.
  179. ;;;   Provide more Lisp programming examples in the manual.
  180. ;;;   Finish the Internals section of the manual (and bring it up to date).
  181. ;;;
  182. ;;;   Tim suggests adding spreadsheet-like features.
  183. ;;;   Implement language modes for Gnuplot, Lisp, Ada, APL, ...?
  184. ;;;
  185.  
  186.  
  187. ;;; For atan series, if x > tan(pi/12) (about 0.268) reduce using the identity
  188. ;;;   atan(x) = atan((x * sqrt(3) - 1) / (sqrt(3) + x)) + pi/6.
  189.  
  190.  
  191. ;;; A better integration algorithm:
  192. ;;;   Use breadth-first instead of depth-first search, as follows:
  193. ;;;    The integral cache allows unfinished integrals in symbolic notation
  194. ;;;    on the righthand side.  An entry with no unfinished integrals on the
  195. ;;;    RHS is "complete"; references to it elsewhere are replaced by the
  196. ;;;    integrated value.  More than one cache entry for the same integral
  197. ;;;    may exist, though if one becomes complete, the others may be deleted.
  198. ;;;    The integrator works by using every applicable rule (such as
  199. ;;;    substitution, parts, linearity, etc.) to generate possible righthand
  200. ;;;    sides, all of which are entered into the cache.  Now, as long as the
  201. ;;;    target integral is not complete (and the time limit has not run out)
  202. ;;;    choose an incomplete integral from the cache and, for every integral
  203. ;;;    appearing in its RHS's, add those integrals to the cache using the
  204. ;;;    same substitition, parts, etc. rules.  The cache should be organized
  205. ;;;    as a priority queue, choosing the "simplest" incomplete integral at
  206. ;;;    each step, or choosing randomly among equally simple integrals.
  207. ;;;    Simplicity equals small size, and few steps removed from the original
  208. ;;;    target integral.  Note that when the integrator finishes, incomplete
  209. ;;;    integrals can be left in the cache, so the algorithm can start where
  210. ;;;    it left off if another similar integral is later requested.
  211. ;;;   Breadth-first search would avoid the nagging problem of, e.g., whether
  212. ;;;   to use parts or substitution first, and which decomposition is best.
  213. ;;;   All are tried, and any path that diverges will quickly be put on the
  214. ;;;   back burner by the priority queue.
  215. ;;;   Note: Probably a good idea to call math-simplify-extended before
  216. ;;;   measuring a formula's simplicity.
  217.  
  218.  
  219.  
  220.  
  221.  
  222.  
  223. ;; Calculator stack.
  224. ;; Entries are 3-lists:  Formula, Height (in lines), Selection (or nil).
  225. (defvar calc-stack '((top-of-stack 1 nil)))
  226.  
  227. ;; Index into calc-stack of "top" of stack.
  228. ;; This is 1 unless calc-truncate-stack has been used.
  229. ;;(defvar calc-stack-top 1)
  230.  
  231. ;; If non-NIL, load the calc-ext module automatically when calc is loaded.
  232. ;;(defvar calc-always-load-extensions nil)
  233.  
  234. ;; If non-NIL, display line numbers in Calculator stack.
  235. ;;(defvar calc-line-numbering t)
  236.  
  237. ;; If non-NIL, break long values across multiple lines in Calculator stack.
  238. ;;(defvar calc-line-breaking t)
  239.  
  240. ;; If NIL, stack display is left-justified.
  241. ;; If 'right, stack display is right-justified.
  242. ;; If 'center, stack display is centered."
  243. ;;(defvar calc-display-just nil)
  244.  
  245. ;; Horizontal origin of displayed stack entries.
  246. ;; In left-justified mode, this is effectively indentation.  (Default 0).
  247. ;; In right-justified mode, this is effectively window width.
  248. ;; In centered mode, center of stack entry is placed here.
  249. ;;(defvar calc-display-origin nil)
  250.  
  251. ;; Radix for entry and display of numbers in calc-mode, 2-36.
  252. ;;(defvar calc-number-radix 10)
  253.  
  254. ;; If non-NIL, leading zeros are provided to pad integers to calc-word-size.
  255. ;;(defvar calc-leading-zeros nil)
  256.  
  257. ;; If non-NIL, group digits in large displayed integers by inserting spaces.
  258. ;; If an integer, group that many digits at a time.
  259. ;; If 't', use 4 for binary and hex, 3 otherwise.
  260. ;;(defvar calc-group-digits nil)
  261.  
  262. ;; The character (in the form of a string) to be used for grouping digits.
  263. ;; This is used only when calc-group-digits mode is on.
  264. ;;(defvar calc-group-char ",")
  265.  
  266. ;; The character (in the form of a string) to be used as a decimal point.
  267. ;;(defvar calc-point-char ".")
  268.  
  269. ;; Format of displayed fractions; a string of one or two of ":" or "/".
  270. ;;(defvar calc-frac-format '(":" nil))
  271.  
  272. ;; If non-NIL, prefer fractional over floating-point results.
  273. ;;(defvar calc-prefer-frac nil)
  274.  
  275. ;; Format of displayed hours-minutes-seconds angles, a format string.
  276. ;; String must contain three %s marks for hours, minutes, seconds respectively.
  277. ;;(defvar calc-hms-format "%s@ %s' %s\"")
  278.  
  279. ;; Format of displayed date forms.
  280. ;;(defvar calc-date-format '((H ":" mm ":" SS pp " ") Www " " Mmm " " D ", " YYYY))
  281.  
  282. ;; Format to use for display of floating-point numbers in calc-mode.
  283. ;; Must be a list of one of the following forms:
  284. ;;  (float 0)      Floating point format, display full precision.
  285. ;;  (float N)      N > 0: Floating point format, at most N significant figures.
  286. ;;  (float -N)     -N < 0: Floating point format, calc-internal-prec - N figs.
  287. ;;  (fix N)        N >= 0: Fixed point format, N places after decimal point.
  288. ;;  (sci 0)        Scientific notation, full precision.
  289. ;;  (sci N)        N > 0: Scientific notation, N significant figures.
  290. ;;  (sci -N)       -N < 0: Scientific notation, calc-internal-prec - N figs.
  291. ;;  (eng 0)        Engineering notation, full precision.
  292. ;;  (eng N)        N > 0: Engineering notation, N significant figures.
  293. ;;  (eng -N)       -N < 0: Engineering notation, calc-internal-prec - N figs.
  294. ;;(defvar calc-float-format '(float 0))
  295.  
  296. ;; Format to use when full precision must be displayed.
  297. ;;(defvar calc-full-float-format '(float 0))
  298.  
  299. ;; Format to use for display of complex numbers in calc-mode.  Must be one of:
  300. ;;   nil            Use (x, y) form.
  301. ;;   i              Use x + yi form.
  302. ;;   j              Use x + yj form.
  303. ;;(defvar calc-complex-format nil)
  304.  
  305. ;; Preferred form, either 'cplx or 'polar, for complex numbers.
  306. ;;(defvar calc-complex-mode 'cplx)
  307.  
  308. ;; If NIL, 1 / 0 is left unsimplified.
  309. ;; If 0, 1 / 0 is changed to inf (zeros are considered positive).
  310. ;; Otherwise, 1 / 0 is changed to uinf (undirected infinity).
  311. ;;(defvar calc-infinite-mode nil)
  312.  
  313. ;; If non-NIL, display vectors of byte-sized integers as strings.
  314. ;;(defvar calc-display-strings nil)
  315.  
  316. ;; If NIL, vector elements are left-justified.
  317. ;; If 'right, vector elements are right-justified.
  318. ;; If 'center, vector elements are centered."
  319. ;;(defvar calc-matrix-just 'center)
  320.  
  321. ;; If non-NIL, display vectors one element per line.
  322. ;;(defvar calc-break-vectors nil)
  323.  
  324. ;; If non-NIL, display long vectors in full.  If NIL, use abbreviated form.
  325. ;;(defvar calc-full-vectors t)
  326.  
  327. ;; If non-NIL, display long vectors in full in the trail.
  328. ;;(defvar calc-full-trail-vectors t)
  329.  
  330. ;; If non-NIL, separate elements of displayed vectors with this string.
  331. ;;(defvar calc-vector-commas ",")
  332.  
  333. ;; If non-NIL, surround displayed vectors with these characters.
  334. ;;(defvar calc-vector-brackets "[]")
  335.  
  336. ;; A list of code-letter symbols that control "big" matrix display.
  337. ;; If 'R is present, display inner brackets for matrices.
  338. ;; If 'O is present, display outer brackets for matrices (above/below).
  339. ;; If 'C is present, display outer brackets for matrices (centered).
  340. ;;(defvar calc-matrix-brackets '(R O))
  341.  
  342. ;; Language or format for entry and display of stack values.  Must be one of:
  343. ;;   nil            Use standard Calc notation.
  344. ;;   flat           Use standard Calc notation, one-line format.
  345. ;;   big         Display formulas in 2-d notation (enter w/std notation).
  346. ;;   unform        Use unformatted display: add(a, mul(b,c)).
  347. ;;   c              Use C language notation.
  348. ;;   pascal         Use Pascal language notation.
  349. ;;   fortran        Use Fortran language notation.
  350. ;;   tex            Use TeX notation.
  351. ;;   eqn        Use eqn notation.
  352. ;;   math           Use Mathematica(tm) notation.
  353. ;;   maple        Use Maple notation.
  354. ;;(defvar calc-language nil)
  355.  
  356. ;; Numeric prefix argument for the command that set calc-language.
  357. ;;(defvar calc-language-option nil)
  358.  
  359. ;; Open-parenthesis string for function call notation.
  360. ;;(defvar calc-function-open "(")
  361.  
  362. ;; Close-parenthesis string for function call notation.
  363. ;;(defvar calc-function-close ")")
  364.  
  365. ;; Function through which to pass strings after formatting.
  366. ;;(defvar calc-language-output-filter nil)
  367.  
  368. ;; Function through which to pass strings before parsing.
  369. ;;(defvar calc-language-input-filter nil)
  370.  
  371. ;; Formatting function used for non-decimal numbers.
  372. ;;(defvar calc-radix-formatter nil)
  373.  
  374. ;; Label to display at left of formula.
  375. ;;(defvar calc-left-label "")
  376.  
  377. ;; Label to display at right of formula.
  378. ;;(defvar calc-right-label "")
  379.  
  380. ;; Minimum number of bits per word, if any, for binary operations in calc-mode.
  381. ;;(defvar calc-word-size 32)
  382.  
  383. ;; Most recently used value of M in a modulo form.
  384. ;;(defvar calc-previous-modulo nil)
  385.  
  386. ;; Type of simplification applied to results.
  387. ;; If 'none, results are not simplified when pushed on the stack.
  388. ;; If 'num, functions are simplified only when args are constant.
  389. ;; If NIL, only fast simplifications are applied.
  390. ;; If 'binary, math-clip is applied if appropriate.
  391. ;; If 'alg, math-simplify is applied.
  392. ;; If 'ext, math-simplify-extended is applied.
  393. ;; If 'units, math-simplify-units is applied.
  394. ;;(defvar calc-simplify-mode nil)
  395.  
  396. ;; If non-NIL, recompute evalto's automatically when necessary.
  397. ;;(defvar calc-auto-recompute t)
  398.  
  399. ;; If non-NIL, display shows unformatted Lisp exprs.  (For debugging)
  400. ;;(defvar calc-display-raw nil)
  401.  
  402. ;; Number of digits of internal precision for calc-mode calculations.
  403. ;;(defvar calc-internal-prec 12)
  404.  
  405. ;; If non-NIL, next operation is Inverse.
  406. ;;(defvar calc-inverse-flag nil)
  407.  
  408. ;; If non-NIL, next operation is Hyperbolic.
  409. ;;(defvar calc-hyperbolic-flag nil)
  410.  
  411. ;; If non-NIL, next operation should not remove its arguments from stack.
  412. ;;(defvar calc-keep-args-flag nil)
  413.  
  414. ;; If deg, angles are in degrees; if rad, angles are in radians.
  415. ;; If hms, angles are in degrees-minutes-seconds.
  416. ;;(defvar calc-angle-mode 'deg)
  417.  
  418. ;; If non-NIL, numeric entry accepts whole algebraic expressions.
  419. ;; If NIL, algebraic expressions must be preceded by "'".
  420. ;;(defvar calc-algebraic-mode nil)
  421.  
  422. ;; Like calc-algebraic-mode except only affects ( and [ keys.
  423. ;;(defvar calc-incomplete-algebraic-mode nil)
  424.  
  425. ;; If non-NIL, inexact numeric computations like sqrt(2) are postponed.
  426. ;; If NIL, computations on numbers always yield numbers where possible.
  427. ;;(defvar calc-symbolic-mode nil)
  428.  
  429. ;; If 'matrix, variables are assumed to be matrix-valued.
  430. ;; If a number, variables are assumed to be NxN matrices.
  431. ;; If 'scalar, variables are assumed to be scalar-valued.
  432. ;; If NIL, symbolic math routines make no assumptions about variables.
  433. ;;(defvar calc-matrix-mode nil)
  434.  
  435. ;; If non-NIL, shifted letter keys are prefix keys rather than normal meanings.
  436. ;;(defvar calc-shift-prefix nil)
  437.  
  438. ;; Initial height of Calculator window.
  439. ;;(defvar calc-window-height 7)
  440.  
  441. ;; If non-NIL, M-x calc creates a window to display Calculator trail.
  442. ;;(defvar calc-display-trail t)
  443.  
  444. ;; If non-NIL, selected sub-formulas are shown by obscuring rest of formula.
  445. ;; If NIL, selected sub-formulas are highlighted by obscuring the sub-formulas.
  446. ;;(defvar calc-show-selections t)
  447.  
  448. ;; If non-NIL, commands operate only on selected portions of formulas.
  449. ;; If NIL, selections displayed but ignored.
  450. ;;(defvar calc-use-selections t)
  451.  
  452. ;; If non-NIL, selection hides deep structure of associative formulas.
  453. ;;(defvar calc-assoc-selections t)
  454.  
  455. ;; If non-NIL, display "Working..." for potentially slow Calculator commands.
  456. ;;(defvar calc-display-working-message 'lots)
  457.  
  458. ;; If non-NIL, automatically execute a "why" command to explain odd results.
  459. ;;(defvar calc-auto-why nil)
  460.  
  461. ;; If non-NIL, display timing information on each slow command.
  462. ;;(defvar calc-timing nil)
  463.  
  464. ;; Floating-point numbers with this positive exponent or higher above the
  465. ;; current precision are displayed in scientific notation in calc-mode.
  466. (defvar calc-display-sci-high 0)
  467.  
  468. ;; Floating-point numbers with this negative exponent or lower are displayed
  469. ;; scientific notation in calc-mode.
  470. (defvar calc-display-sci-low -3)
  471.  
  472.  
  473. ;; List of used-defined strings to append to Calculator mode line.
  474. (defvar calc-other-modes nil)
  475.  
  476. ;; List of strings for Y prefix help.
  477. (defvar calc-Y-help-msgs nil)
  478.  
  479. ;; T if calc-settings-file has been loaded yet.
  480. (defvar calc-loaded-settings-file nil)
  481.  
  482.  
  483.  
  484. (defconst calc-mode-var-list '((calc-always-load-extensions nil)
  485.                    (calc-mode-save-mode local)
  486.                    (calc-line-numbering t)
  487.                    (calc-line-breaking t)
  488.                    (calc-display-just nil)
  489.                    (calc-display-origin nil)
  490.                    (calc-left-label "")
  491.                    (calc-right-label "")
  492.                    (calc-number-radix 10)
  493.                    (calc-leading-zeros nil)
  494.                    (calc-group-digits nil)
  495.                    (calc-group-char ",")
  496.                    (calc-point-char ".")
  497.                    (calc-frac-format (":" nil))
  498.                    (calc-prefer-frac nil)
  499.                    (calc-hms-format "%s@ %s' %s\"")
  500.                    (calc-date-format ((H ":" mm C SS pp " ")
  501.                           Www " " Mmm " " D ", " YYYY))
  502.                    (calc-standard-date-formats
  503.                 ("N"
  504.                  "<H:mm:SSpp >Www Mmm D, YYYY"
  505.                  "D Mmm YYYY<, h:mm:SS>"
  506.                  "Www Mmm BD< hh:mm:ss> YYYY"
  507.                  "M/D/Y< H:mm:SSpp>"
  508.                  "D.M.Y< h:mm:SS>"
  509.                  "M-D-Y< H:mm:SSpp>"
  510.                  "D-M-Y< h:mm:SS>"
  511.                  "j<, h:mm:SS>"
  512.                  "YYddd< hh:mm:ss>"))
  513.                    (calc-float-format (float 0))
  514.                    (calc-full-float-format (float 0))
  515.                    (calc-complex-format nil)
  516.                    (calc-matrix-just center)
  517.                    (calc-full-vectors t)
  518.                    (calc-full-trail-vectors t)
  519.                    (calc-break-vectors nil)
  520.                    (calc-vector-commas ",")
  521.                    (calc-vector-brackets "[]")
  522.                    (calc-matrix-brackets (R O))
  523.                    (calc-complex-mode cplx)
  524.                    (calc-infinite-mode nil)
  525.                    (calc-display-strings nil)
  526.                    (calc-simplify-mode nil)
  527.                    (calc-auto-recompute t)
  528.                    (calc-word-size 32)
  529.                    (calc-previous-modulo nil)
  530.                    (calc-display-raw nil)
  531.                    (calc-internal-prec 12)
  532.                    (calc-angle-mode deg)
  533.                    (calc-algebraic-mode nil)
  534.                    (calc-incomplete-algebraic-mode nil)
  535.                    (calc-symbolic-mode nil)
  536.                    (calc-matrix-mode nil)
  537.                    (calc-autorange-units nil)
  538.                    (calc-shift-prefix nil)
  539.                    (calc-window-height 7)
  540.                    (calc-was-keypad-mode nil)
  541.                    (calc-full-mode nil)
  542.                    (calc-language nil)
  543.                    (calc-language-option nil)
  544.                    (calc-user-parse-tables nil)
  545.                    (calc-show-selections t)
  546.                    (calc-use-selections t)
  547.                    (calc-assoc-selections t)
  548.                    (calc-display-trail t)
  549.                    (calc-display-working-message lots)
  550.                    (calc-auto-why 'maybe)
  551.                    (calc-timing nil)
  552.                    (calc-gnuplot-default-device "default")
  553.                    (calc-gnuplot-default-output "STDOUT")
  554.                    (calc-gnuplot-print-device "postscript")
  555.                    (calc-gnuplot-print-output "auto")
  556.                    (calc-gnuplot-geometry nil)
  557.                    (calc-graph-default-resolution 15)
  558.                    (calc-graph-default-resolution-3d 5)
  559.                    (calc-invocation-macro nil)))
  560.  
  561. (defconst calc-local-var-list '(calc-stack
  562.                 calc-stack-top
  563.                 calc-undo-list
  564.                 calc-redo-list
  565.                 calc-always-load-extensions
  566.                 calc-mode-save-mode
  567.                 calc-display-raw
  568.                 calc-line-numbering
  569.                 calc-line-breaking
  570.                 calc-display-just
  571.                 calc-display-origin
  572.                 calc-left-label
  573.                 calc-right-label
  574.                 calc-auto-why
  575.                 calc-algebraic-mode
  576.                 calc-incomplete-algebraic-mode
  577.                 calc-symbolic-mode
  578.                 calc-matrix-mode
  579.                 calc-inverse-flag
  580.                 calc-hyperbolic-flag
  581.                 calc-keep-args-flag
  582.                 calc-angle-mode
  583.                 calc-number-radix
  584.                 calc-leading-zeros
  585.                 calc-group-digits
  586.                 calc-group-char
  587.                 calc-point-char
  588.                 calc-frac-format
  589.                 calc-prefer-frac
  590.                 calc-hms-format
  591.                 calc-date-format
  592.                 calc-standard-date-formats
  593.                 calc-float-format
  594.                 calc-full-float-format
  595.                 calc-complex-format
  596.                 calc-matrix-just
  597.                 calc-full-vectors
  598.                 calc-full-trail-vectors
  599.                 calc-break-vectors
  600.                 calc-vector-commas
  601.                 calc-vector-brackets
  602.                 calc-matrix-brackets
  603.                 calc-complex-mode
  604.                 calc-infinite-mode
  605.                 calc-display-strings
  606.                 calc-simplify-mode
  607.                 calc-auto-recompute
  608.                 calc-autorange-units
  609.                 calc-show-plain
  610.                 calc-show-selections
  611.                 calc-use-selections
  612.                 calc-assoc-selections
  613.                 calc-word-size
  614.                 calc-internal-prec))
  615.  
  616.  
  617. (defun calc-init-base ()
  618.  
  619.   ;; Set up the standard keystroke (M-#) to run the Calculator, if that key
  620.   ;; has not yet been bound to anything.  For best results, the user should
  621.   ;; do this before Calc is even loaded, so that M-# can auto-load Calc.
  622.   (or (global-key-binding "\e#")
  623.       (global-set-key "\e#" 'calc-dispatch))
  624.  
  625.   ;; Set up the autoloading linkage.
  626.   (let ((name (and (fboundp 'calc-dispatch)
  627.            (eq (car-safe (symbol-function 'calc-dispatch)) 'autoload)
  628.            (nth 1 (symbol-function 'calc-dispatch))))
  629.     (p load-path))
  630.  
  631.     ;; If Calc files exist on the load-path, we're all set.
  632.     (while (and p (not (file-exists-p
  633.             (expand-file-name "calc-misc.elc" (car p)))))
  634.       (setq p (cdr p)))
  635.     (or p
  636.  
  637.     ;; If Calc is autoloaded using a path name, look there for Calc files.
  638.     ;; This works for both relative ("calc/calc.elc") and absolute paths.
  639.     (and name (file-name-directory name)
  640.          (let ((p2 load-path)
  641.            (name2 (concat (file-name-directory name)
  642.                   "calc-misc.elc")))
  643.            (while (and p2 (not (file-exists-p
  644.                     (expand-file-name name2 (car p2)))))
  645.          (setq p2 (cdr p2)))
  646.            (if p2
  647.            (setq load-path (nconc load-path
  648.                       (list
  649.                        (directory-file-name
  650.                         (file-name-directory
  651.                          (expand-file-name
  652.                           name (car p2))))))))))
  653.  
  654.     ;; If calc-autoload-directory is given, use that (and hope it works!).
  655.     (and calc-autoload-directory
  656.          (not (equal calc-autoload-directory ""))
  657.          (setq load-path (nconc load-path
  658.                     (list (directory-file-name
  659.                        calc-autoload-directory)))))))
  660.  
  661.   ;; The following modes use specially-formatted data.
  662.   (put 'calc-mode 'mode-class 'special)
  663.   (put 'calc-trail-mode 'mode-class 'special)
  664.   
  665.   ;; Define "inexact-result" as an e-lisp error symbol.
  666.   (put 'inexact-result 'error-conditions '(error inexact-result calc-error))
  667.   (put 'inexact-result 'error-message "Calc internal error (inexact-result)")
  668.   
  669.   ;; Define "math-overflow" and "math-underflow" as e-lisp error symbols.
  670.   (put 'math-overflow 'error-conditions '(error math-overflow calc-error))
  671.   (put 'math-overflow 'error-message "Floating-point overflow occurred")
  672.   (put 'math-underflow 'error-conditions '(error math-underflow calc-error))
  673.   (put 'math-underflow 'error-message "Floating-point underflow occurred")
  674.   
  675.   (setq calc-version "2.02a"
  676.     calc-version-date "Mon May 31 1993"
  677.     calc-trail-pointer nil        ; "Current" entry in trail buffer.
  678.         calc-trail-overlay nil        ; Value of overlay-arrow-string.
  679.     calc-was-split nil        ; Had multiple windows before Calc.
  680.         calc-undo-list nil        ; List of previous operations for undo.
  681.         calc-redo-list nil        ; List of recent undo operations.
  682.         calc-main-buffer nil        ; Pointer to Calculator buffer.
  683.     calc-trail-buffer nil        ; Pointer to Calc Trail buffer.
  684.         calc-why nil            ; Explanations of most recent errors.
  685.         calc-next-why nil
  686.     calc-inverse-flag nil
  687.     calc-hyperbolic-flag nil
  688.     calc-keep-args-flag nil
  689.     calc-function-open "("
  690.     calc-function-close ")"
  691.     calc-language-output-filter nil
  692.     calc-language-input-filter nil
  693.     calc-radix-formatter nil
  694.         calc-last-kill nil        ; Last number killed in calc-mode.
  695.         calc-previous-alg-entry nil    ; Previous algebraic entry.
  696.         calc-dollar-values nil        ; Values to be used for '$'.
  697.         calc-dollar-used nil        ; Highest order of '$' that occurred.
  698.     calc-hashes-used nil            ; Highest order of '#' that occurred.
  699.         calc-quick-prev-results nil    ; Previous results from Quick Calc.
  700.     calc-said-hello nil        ; Has welcome message been said yet?
  701.     calc-executing-macro nil    ; Kbd macro executing from "K" key.
  702.     calc-any-selections nil     ; Nil means no selections present.
  703.     calc-help-phase 0        ; Count of consecutive "?" keystrokes.
  704.     calc-full-help-flag nil        ; Executing calc-full-help?
  705.     calc-refresh-count 0        ; Count of calc-refresh calls.
  706.     calc-display-dirty nil
  707.     calc-prepared-composition nil
  708.     calc-selection-cache-default-entry nil
  709.     calc-embedded-info nil
  710.     calc-embedded-active nil
  711.     calc-standalone-flag nil
  712.     var-EvalRules nil
  713.     math-eval-rules-cache-tag t
  714.     math-radix-explicit-format t
  715.     math-expr-function-mapping nil
  716.     math-expr-variable-mapping nil
  717.     math-read-expr-quotes nil
  718.     math-working-step nil
  719.     math-working-step-2 nil
  720.         var-i '(special-const (math-imaginary 1))
  721.         var-pi '(special-const (math-pi))
  722.         var-e '(special-const (math-e))
  723.     var-phi '(special-const (math-phi))
  724.         var-gamma '(special-const (math-gamma-const))
  725.     var-Modes '(special-const (math-get-modes-vec)))
  726.  
  727.   (mapcar (function (lambda (v) (or (boundp (car v)) (set (car v) (nth 1 v)))))
  728.       calc-mode-var-list)
  729.   (mapcar (function (lambda (v) (or (boundp v) (set v nil))))
  730.       calc-local-var-list)
  731.  
  732.   (if (boundp 'calc-mode-map)
  733.       nil
  734.     (setq calc-mode-map (make-keymap))
  735.     (suppress-keymap calc-mode-map t)
  736.     (define-key calc-mode-map "+" 'calc-plus)
  737.     (define-key calc-mode-map "-" 'calc-minus)
  738.     (define-key calc-mode-map "*" 'calc-times)
  739.     (define-key calc-mode-map "/" 'calc-divide)
  740.     (define-key calc-mode-map "%" 'calc-mod)
  741.     (define-key calc-mode-map "&" 'calc-inv)
  742.     (define-key calc-mode-map "^" 'calc-power)
  743.     (define-key calc-mode-map "\M-%" 'calc-percent)
  744.     (define-key calc-mode-map "e" 'calcDigit-start)
  745.     (define-key calc-mode-map "i" 'calc-info)
  746.     (define-key calc-mode-map "n" 'calc-change-sign)
  747.     (define-key calc-mode-map "q" 'calc-quit)
  748.     (define-key calc-mode-map "Y" 'nil)
  749.     (define-key calc-mode-map "Y?" 'calc-shift-Y-prefix-help)
  750.     (define-key calc-mode-map "?" 'calc-help)
  751.     (define-key calc-mode-map " " 'calc-enter)
  752.     (define-key calc-mode-map "'" 'calc-algebraic-entry)
  753.     (define-key calc-mode-map "$" 'calc-auto-algebraic-entry)
  754.     (define-key calc-mode-map "\"" 'calc-auto-algebraic-entry)
  755.     (define-key calc-mode-map "\t" 'calc-roll-down)
  756.     (define-key calc-mode-map "\M-\t" 'calc-roll-up)
  757.     (define-key calc-mode-map "\C-m" 'calc-enter)
  758.     (define-key calc-mode-map "\M-\C-m" 'calc-last-args-stub)
  759.     (define-key calc-mode-map "\C-j" 'calc-over)
  760.  
  761.     (mapcar (function
  762.          (lambda (x)
  763.            (define-key calc-mode-map (char-to-string x) 'undefined)))
  764.         "lOW")
  765.     (mapcar (function
  766.          (lambda (x)
  767.            (define-key calc-mode-map (char-to-string x)
  768.          'calc-missing-key)))
  769.         (concat "ABCDEFGHIJKLMNPQRSTUVXZabcdfghjkmoprstuvwxyz"
  770.             ":\\|!()[]<>{},;=~`\C-k\M-k\C-w\M-w\C-y\C-_"))
  771.     (mapcar (function
  772.          (lambda (x)
  773.            (define-key calc-mode-map (char-to-string x) 'calcDigit-start)))
  774.         "_0123456789.#@")
  775.  
  776.     (setq calc-digit-map (make-keymap))
  777.     (let ((m1 calc-digit-map)
  778.       (m2 calc-mode-map)
  779.       (i 0))
  780.       (if (consp m1) (setq m1 (nth 1 m1)))
  781.       (if (consp m2) (setq m2 (nth 1 m2)))
  782.       (while (< i 128)
  783.     (aset m1 i
  784.           (if (eq (aref m2 i) 'undefined)
  785.           'undefined 'calcDigit-nondigit))
  786.     (setq i (1+ i))))
  787.     (mapcar (function
  788.          (lambda (x)
  789.            (define-key calc-digit-map (char-to-string x)
  790.          'calcDigit-key)))
  791.         "_0123456789.e+-:n#@oh'\"mspM")
  792.     (mapcar (function
  793.          (lambda (x)
  794.            (define-key calc-digit-map (char-to-string x)
  795.          'calcDigit-letter)))
  796.         "abcdfgijklqrtuvwxyzABCDEFGHIJKLNOPQRSTUVWXYZ")
  797.     (define-key calc-digit-map "'" 'calcDigit-algebraic)
  798.     (define-key calc-digit-map "`" 'calcDigit-edit)
  799.     (define-key calc-digit-map "\C-g" 'abort-recursive-edit)
  800.  
  801.     (mapcar (function
  802.          (lambda (x)
  803.            (condition-case err
  804.            (progn
  805.              (define-key calc-digit-map x 'calcDigit-backspace)
  806.              (define-key calc-mode-map x 'calc-pop)
  807.              (if (stringp x)
  808.              (define-key calc-mode-map (concat "\e" x)
  809.                'calc-pop-above)))
  810.          (error nil))))
  811.         (if calc-scan-for-dels
  812.         (append (where-is-internal 'delete-backward-char global-map)
  813.             (where-is-internal 'backward-delete-char global-map)
  814.             '("\C-d"))
  815.           '("\177" "\C-d")))
  816.  
  817.     (setq calc-dispatch-map (make-keymap))
  818.     (calc-build-dispatch-map calc-dispatch-map)
  819.     (setq calc-dispatch-meta-map (make-sparse-keymap))
  820.     (calc-build-dispatch-map calc-dispatch-meta-map)
  821.     (define-key calc-dispatch-map "\e" calc-dispatch-meta-map))
  822.  
  823.   (autoload 'calc-extensions "calc-ext")
  824.   (autoload 'calc-need-macros "calc-macs")
  825.  
  826. ;;;; (Autoloads here)
  827.   (mapcar (function (lambda (x)
  828.     (mapcar (function (lambda (func)
  829.       (autoload func (car x)))) (cdr x))))
  830.     '(
  831.  
  832.  ("calc-aent" calc-Need-calc-aent calc-alg-digit-entry calc-alg-entry
  833. calc-check-user-syntax calc-do-alg-entry calc-do-calc-eval
  834. calc-do-quick-calc calc-match-user-syntax math-build-parse-table
  835. math-find-user-tokens math-read-expr-list math-read-exprs math-read-if
  836. math-read-token math-remove-dashes)
  837.  
  838.  ("calc-misc" calc-Need-calc-misc calc-delete-windows-keep
  839. calc-do-handle-whys calc-do-refresh calc-num-prefix-name
  840. calc-record-list calc-record-why calc-report-bug calc-roll-down-stack
  841. calc-roll-up-stack calc-temp-minibuffer-message calcFunc-floor
  842. calcFunc-inv calcFunc-trunc math-concat math-constp math-div2
  843. math-div2-bignum math-do-working math-evenp math-fixnatnump
  844. math-fixnump math-floor math-imod math-ipow math-looks-negp math-mod
  845. math-negp math-posp math-pow math-read-radix-digit math-reject-arg
  846. math-trunc math-zerop)
  847.  
  848. ))
  849.  
  850.   (mapcar (function (lambda (x)
  851.     (mapcar (function (lambda (cmd)
  852.       (autoload cmd (car x) nil t))) (cdr x))))
  853.     '(
  854.  
  855.  ("calc-aent" calc-algebraic-entry calc-auto-algebraic-entry
  856. calcDigit-algebraic calcDigit-edit)
  857.  
  858.  ("calc-misc" another-calc calc-big-or-small calc-dispatch-help
  859. calc-help calc-info calc-info-summary calc-inv calc-last-args-stub
  860. calc-missing-key calc-mod calc-other-window calc-over calc-percent
  861. calc-pop-above calc-power calc-roll-down calc-roll-up
  862. calc-shift-Y-prefix-help calc-tutorial calcDigit-letter
  863. report-calc-bug)
  864.  
  865. ))
  866.  
  867. )
  868.  
  869. ;;; (require 'calc-macs)
  870.  
  871. (defun calc-build-dispatch-map (map)
  872.   (mapcar (function
  873.        (lambda (x)
  874.          (define-key map (char-to-string (car x)) (cdr x))
  875.          (define-key map (char-to-string (- (car x) ?a -1)) (cdr x))))
  876.       '( ( ?a . calc-embedded-activate )
  877.          ( ?b . calc-big-or-small )
  878.          ( ?c . calc )
  879.          ( ?d . calc-embedded-duplicate )
  880.          ( ?e . calc-embedded )
  881.          ( ?f . calc-embedded-new-formula )
  882.          ( ?h . calc-dispatch-help )
  883.          ( ?i . calc-info )
  884.          ( ?j . calc-embedded-select )
  885.          ( ?k . calc-keypad )
  886.          ( ?l . calc-load-everything )
  887.          ( ?n . calc-embedded-next )
  888.          ( ?o . calc-other-window )
  889.          ( ?p . calc-embedded-previous )
  890.          ( ?q . quick-calc )
  891.          ( ?r . calc-grab-rectangle )
  892.          ( ?s . calc-info-summary )
  893.          ( ?t . calc-tutorial )
  894.          ( ?u . calc-embedded-update-formula )
  895.          ( ?w . calc-embedded-word )
  896.          ( ?x . calc-quit )
  897.          ( ?y . calc-copy-to-buffer )
  898.          ( ?z . calc-user-invocation ) ))
  899.   (define-key map "g" 'calc-grab-region)  ; but not C-g!
  900.   (define-key map "m" 'read-kbd-macro)
  901.   (define-key map "=" 'calc-embedded-update-formula)
  902.   (define-key map "'" 'calc-embedded-new-formula)
  903.   (define-key map "`" 'calc-embedded-edit)
  904.   (define-key map ":" 'calc-grab-sum-down)
  905.   (define-key map "_" 'calc-grab-sum-across)
  906.   (define-key map "0" 'calc-reset)
  907.   (define-key map "#" 'calc-same-interface)
  908.   (define-key map "?" 'calc-dispatch-help)
  909. )
  910.  
  911. (calc-init-base)
  912.  
  913.  
  914. ;;;###autoload (global-set-key "\e#" 'calc-dispatch)
  915.  
  916. ;;;###autoload
  917. (defun calc-dispatch (&optional arg)
  918.   "Invoke the GNU Emacs Calculator.  See calc-dispatch-help for details."
  919.   (interactive "P")
  920.   (sit-for echo-keystrokes)
  921.   (condition-case err   ; look for other keys bound to calc-dispatch
  922.       (let ((keys (this-command-keys)))
  923.     (or (not (stringp keys))
  924.         (string-match "\\`\C-u\\|\\`\e[-0-9#]\\|`[\M--\M-0-\M-9]" keys)
  925.         (eq (lookup-key calc-dispatch-map keys) 'calc-same-interface)
  926.         (progn
  927.           (and (string-match "\\`[\C-@-\C-_]" keys)
  928.            (symbolp
  929.             (lookup-key calc-dispatch-map (substring keys 0 1)))
  930.            (define-key calc-dispatch-map (substring keys 0 1) nil))
  931.           (define-key calc-dispatch-map keys 'calc-same-interface))))
  932.     (error nil))
  933.   (calc-do-dispatch arg)
  934. )
  935.  
  936. (defun calc-do-dispatch (arg)
  937.   (let ((key (calc-read-key-sequence
  938.           (if calc-dispatch-help
  939.           "Calc options: Calc, Keypad, Quick, Embed; eXit; Info, Tutorial; Grab; ?=more"
  940.         (format "%s  (Type ? for a list of Calc options)"
  941.             (key-description (this-command-keys))))
  942.           calc-dispatch-map)))
  943.     (setq key (lookup-key calc-dispatch-map key))
  944.     (message "")
  945.     (if key
  946.     (progn
  947.       (or (commandp key) (calc-extensions))
  948.       (call-interactively key))
  949.       (beep)))
  950. )
  951. (setq calc-dispatch-help nil)
  952.  
  953. (defun calc-read-key-sequence (prompt map)
  954.   (let ((prompt2 (format "%s " (key-description (this-command-keys))))
  955.     (glob (current-global-map))
  956.     (loc (current-local-map)))
  957.     (or (input-pending-p) (message prompt))
  958.     (setq unread-command-char (read-char))
  959.     (unwind-protect
  960.     (progn
  961.       (use-global-map map)
  962.       (use-local-map nil)
  963.       (read-key-sequence
  964.        (if (commandp (key-binding (char-to-string unread-command-char)))
  965.            "" prompt2)))
  966.       (use-global-map glob)
  967.       (use-local-map loc)))
  968. )
  969.  
  970.  
  971.  
  972. (defun calc-mode ()
  973.   "Calculator major mode.
  974.  
  975. This is an RPN calculator featuring arbitrary-precision integer, rational,
  976. floating-point, complex, matrix, and symbolic arithmetic.
  977.  
  978. RPN calculation:  2 RET 3 +    produces 5.
  979. Algebraic style:  ' 2+3 RET    produces 5.
  980.  
  981. Basic operators are +, -, *, /, ^, & (reciprocal), % (modulo), n (change-sign).
  982.  
  983. Press ? repeatedly for more complete help.  Press `h i' to read the
  984. Calc manual on-line, `h s' to read the summary, or `h t' for the tutorial.
  985.  
  986. Notations:  3.14e6     3.14 * 10^6
  987.             _23        negative number -23 (or type `23 n')
  988.             17:3       the fraction 17/3
  989.             5:2:3      the fraction 5 and 2/3
  990.             16#12C     the integer 12C base 16 = 300 base 10
  991.             8#177:100  the fraction 177:100 base 8 = 127:64 base 10
  992.             (2, 4)     complex number 2 + 4i
  993.             (2; 4)     polar complex number (r; theta)
  994.             [1, 2, 3]  vector  ([[1, 2], [3, 4]] is a matrix)
  995.             [1 .. 4)   semi-open interval, 1 <= x < 4
  996.             2 +/- 3    (p key) number with mean 2, standard deviation 3
  997.             2 mod 3    (M key) number 2 computed modulo 3
  998.         <1 jan 91> Date form (enter using ' key)
  999.  
  1000.  
  1001. \\{calc-mode-map}
  1002. "
  1003.   (interactive)
  1004.   (mapcar (function
  1005.        (lambda (v) (set-default v (symbol-value v)))) calc-local-var-list)
  1006.   (kill-all-local-variables)
  1007.   (use-local-map (if (eq calc-algebraic-mode 'total)
  1008.              (progn (calc-extensions) calc-alg-map) calc-mode-map))
  1009.   (mapcar (function (lambda (v) (make-local-variable v))) calc-local-var-list)
  1010.   (make-local-variable 'overlay-arrow-position)
  1011.   (make-local-variable 'overlay-arrow-string)
  1012.   (setq truncate-lines t)
  1013.   (setq buffer-read-only t)
  1014.   (setq major-mode 'calc-mode)
  1015.   (setq mode-name "Calculator")
  1016.   (setq calc-stack-top (length (or (memq (assq 'top-of-stack calc-stack)
  1017.                      calc-stack)
  1018.                    (setq calc-stack (list (list 'top-of-stack
  1019.                                 1 nil))))))
  1020.   (setq calc-stack-top (- (length calc-stack) calc-stack-top -1))
  1021.   (or calc-loaded-settings-file
  1022.       (string-match "\\.emacs" calc-settings-file)
  1023.       (progn
  1024.     (setq calc-loaded-settings-file t)
  1025.     (load calc-settings-file t)))   ; t = missing-ok
  1026.   (if (and (eq window-system 'x) (fboundp 'x-paste-text))
  1027.       (substitute-key-definition 'x-paste-text 'calc-x-paste-text
  1028.                  mouse-map))
  1029.   (let ((p command-line-args))
  1030.     (while p
  1031.       (and (equal (car p) "-f")
  1032.        (string-match "calc" (nth 1 p))
  1033.        (string-match "full" (nth 1 p))
  1034.        (setq calc-standalone-flag t))
  1035.       (setq p (cdr p))))
  1036.   (run-hooks 'calc-mode-hook)
  1037.   (calc-refresh t)
  1038.   (calc-set-mode-line)
  1039.   ;; The calc-defs variable is a relic.  Use calc-define properties instead.
  1040.   (if (and (boundp 'calc-defs)
  1041.        calc-defs)
  1042.       (progn
  1043.     (message "Evaluating calc-defs...")
  1044.     (calc-need-macros)
  1045.     (eval (cons 'progn calc-defs))
  1046.     (setq calc-defs nil)
  1047.     (calc-set-mode-line)))
  1048.   (calc-check-defines)
  1049. )
  1050.  
  1051. (defun calc-check-defines ()
  1052.   (if (symbol-plist 'calc-define)
  1053.       (let ((plist (copy-sequence (symbol-plist 'calc-define))))
  1054.     (while (and plist (null (nth 1 plist)))
  1055.       (setq plist (cdr (cdr plist))))
  1056.     (if plist
  1057.         (save-excursion
  1058.           (calc-extensions)
  1059.           (calc-need-macros)
  1060.           (set-buffer "*Calculator*")
  1061.           (while plist
  1062.         (put 'calc-define (car plist) nil)
  1063.         (eval (nth 1 plist))
  1064.         (setq plist (cdr (cdr plist))))
  1065.           ;; See if this has added any more calc-define properties.
  1066.           (calc-check-defines))
  1067.       (setplist 'calc-define nil))))
  1068. )
  1069. (setq calc-check-defines 'calc-check-defines)  ; suitable for run-hooks
  1070.  
  1071. (defun calc-trail-mode (&optional buf)
  1072.   "Calc Trail mode.
  1073. This mode is used by the *Calc Trail* buffer, which records all results
  1074. obtained by the GNU Emacs Calculator.
  1075.  
  1076. Calculator commands beginning with the `t' key are used to manipulate
  1077. the Trail.
  1078.  
  1079. This buffer uses the same key map as the *Calculator* buffer; calculator
  1080. commands given here will actually operate on the *Calculator* stack."
  1081.   (interactive)
  1082.   (fundamental-mode)
  1083.   (use-local-map calc-mode-map)
  1084.   (setq major-mode 'calc-trail-mode)
  1085.   (setq mode-name "Calc Trail")
  1086.   (setq truncate-lines t)
  1087.   (setq buffer-read-only t)
  1088.   (make-local-variable 'overlay-arrow-position)
  1089.   (make-local-variable 'overlay-arrow-string)
  1090.   (if buf
  1091.       (progn
  1092.     (make-local-variable 'calc-main-buffer)
  1093.     (setq calc-main-buffer buf)))
  1094.   (if (= (buffer-size) 0)
  1095.       (let ((buffer-read-only nil))
  1096.     (insert "Emacs Calculator v" calc-version " by Dave Gillespie, "
  1097.         "installed " calc-installed-date "\n")))
  1098.   (run-hooks 'calc-trail-mode-hook)
  1099. )
  1100.  
  1101. (defun calc-create-buffer ()
  1102.   (set-buffer (get-buffer-create "*Calculator*"))
  1103.   (or (eq major-mode 'calc-mode)
  1104.       (calc-mode))
  1105.   (setq max-lisp-eval-depth (max max-lisp-eval-depth 1000))
  1106.   (if calc-always-load-extensions
  1107.       (calc-extensions))
  1108.   (if calc-language
  1109.       (progn
  1110.     (calc-extensions)
  1111.     (calc-set-language calc-language calc-language-option t)))
  1112. )
  1113.  
  1114. ;;;###autoload
  1115. (defun calc (&optional arg full-display interactive)
  1116.   "The Emacs Calculator.  Full documentation is listed under \"calc-mode\"."
  1117.   (interactive "P")
  1118.   (if arg
  1119.       (or (eq arg 0)
  1120.       (progn
  1121.         (calc-extensions)
  1122.         (if (= (prefix-numeric-value arg) -1)
  1123.         (calc-grab-region (region-beginning) (region-end) nil)
  1124.           (if (= (prefix-numeric-value arg) -2)
  1125.           (calc-keypad)))))
  1126.     (if (get-buffer-window "*Calc Keypad*")
  1127.     (progn
  1128.       (calc-keypad)
  1129.       (set-buffer (window-buffer (selected-window)))))
  1130.     (if (eq major-mode 'calc-mode)
  1131.     (calc-quit)
  1132.       (let ((oldbuf (current-buffer)))
  1133.     (calc-create-buffer)
  1134.     (setq calc-was-keypad-mode nil)
  1135.     (if (or (eq full-display t)
  1136.         (and (null full-display) calc-full-mode))
  1137.         (switch-to-buffer (current-buffer) t)
  1138.       (if (get-buffer-window (current-buffer))
  1139.           (select-window (get-buffer-window (current-buffer)))
  1140.         (setq calc-was-split nil)
  1141.         (if (and (boundp 'calc-window-hook) calc-window-hook)
  1142.         (run-hooks 'calc-window-hook)
  1143.           (let ((w (get-largest-window)))
  1144.         (if (and pop-up-windows
  1145.              (> (window-height w)
  1146.                 (+ window-min-height calc-window-height 2)))
  1147.             (progn
  1148.               (or (one-window-p)
  1149.               (setq calc-was-split (list w (window-height w)
  1150.                              (selected-window))))
  1151.               (setq w (split-window w
  1152.                         (- (window-height w)
  1153.                            calc-window-height 2)
  1154.                         nil))
  1155.               (set-window-buffer w (current-buffer))
  1156.               (select-window w))
  1157.           (pop-to-buffer (current-buffer)))))))
  1158.     (save-excursion
  1159.       (set-buffer (calc-trail-buffer))
  1160.       (and calc-display-trail
  1161.            (= (window-width) (screen-width))
  1162.            (calc-trail-display 1 t)))
  1163.     (message "Welcome to the GNU Emacs Calculator!  Press `?' or `h' for help, `q' to quit.")
  1164.     (run-hooks 'calc-start-hook)
  1165.     (and (windowp full-display)
  1166.          (window-point full-display)
  1167.          (select-window full-display))
  1168.     (calc-check-defines)
  1169.     (and calc-said-hello
  1170.          (or (interactive-p) interactive)
  1171.          (progn
  1172.            (sit-for 2)
  1173.            (message "")))
  1174.     (setq calc-said-hello t))))
  1175. )
  1176.  
  1177. ;;;###autoload
  1178. (defun full-calc ()
  1179.   "Invoke the Calculator and give it a full-sized window."
  1180.   (interactive)
  1181.   (calc nil t (interactive-p))
  1182. )
  1183.  
  1184. (defun calc-same-interface (arg)
  1185.   "Invoke the Calculator using the most recent interface (calc or calc-keypad)."
  1186.   (interactive "P")
  1187.   (if (and (equal (buffer-name) "*Gnuplot Trail*")
  1188.        (> (recursion-depth) 0))
  1189.       (exit-recursive-edit)
  1190.     (if (eq major-mode 'calc-edit-mode)
  1191.     (calc-edit-finish arg)
  1192.       (if (eq major-mode 'MacEdit-mode)
  1193.       (MacEdit-finish-edit)
  1194.     (if calc-was-keypad-mode
  1195.         (calc-keypad)
  1196.       (calc arg calc-full-mode t)))))
  1197. )
  1198.  
  1199.  
  1200. (defun calc-quit (&optional non-fatal)
  1201.   (interactive)
  1202.   (and calc-standalone-flag (not non-fatal)
  1203.        (save-buffers-kill-emacs nil))
  1204.   (if (and (equal (buffer-name) "*Gnuplot Trail*")
  1205.        (> (recursion-depth) 0))
  1206.       (exit-recursive-edit))
  1207.   (if (eq major-mode 'calc-edit-mode)
  1208.       (calc-edit-cancel)
  1209.     (if (eq major-mode 'MacEdit-mode)
  1210.     (MacEdit-cancel-edit)
  1211.       (if (and (interactive-p)
  1212.            calc-embedded-info
  1213.            (eq (current-buffer) (aref calc-embedded-info 0)))
  1214.       (calc-embedded nil)
  1215.     (or (eq major-mode 'calc-mode)
  1216.         (calc-create-buffer))
  1217.     (run-hooks 'calc-end-hook)
  1218.     (setq calc-undo-list nil calc-redo-list nil)
  1219.     (mapcar (function (lambda (v) (set-default v (symbol-value v))))
  1220.         calc-local-var-list)
  1221.     (let ((buf (current-buffer))
  1222.           (win (get-buffer-window (current-buffer)))
  1223.           (kbuf (get-buffer "*Calc Keypad*")))
  1224.       (delete-windows-on (calc-trail-buffer))
  1225.       (if (and win
  1226.            (< (window-height win) (1- (screen-height)))
  1227.            (= (window-width win) (screen-width))  ; avoid calc-keypad
  1228.            (not (get-buffer-window "*Calc Keypad*")))
  1229.           (setq calc-window-height (- (window-height win) 2)))
  1230.       (if calc-was-split
  1231.           (calc-delete-windows-keep buf kbuf)
  1232.         (delete-windows-on buf)
  1233.         (delete-windows-on kbuf))
  1234.       (bury-buffer buf)
  1235.       (bury-buffer calc-trail-buffer)
  1236.       (and kbuf (bury-buffer kbuf))))))
  1237. )
  1238.  
  1239. ;;;###autoload
  1240. (defun quick-calc ()
  1241.   "Do a quick calculation in the minibuffer without invoking full Calculator."
  1242.   (interactive)
  1243.   (calc-do-quick-calc)
  1244. )
  1245.  
  1246. ;;;###autoload
  1247. (defun calc-eval (str &optional separator &rest args)
  1248.   "Do a quick calculation and return the result as a string.
  1249. Return value will either be the formatted result in string form,
  1250. or a list containing a character position and an error message in string form."
  1251.   (calc-do-calc-eval str separator args)
  1252. )
  1253.  
  1254. ;;;###autoload
  1255. (defun calc-keypad ()
  1256.   "Invoke the Calculator in \"visual keypad\" mode.
  1257. This is most useful in the X window system.
  1258. In this mode, click on the Calc \"buttons\" using the left mouse button.
  1259. Or, position the cursor manually and do M-x calc-keypad-press."
  1260.   (interactive)
  1261.   (calc-extensions)
  1262.   (calc-do-keypad calc-full-mode (interactive-p))
  1263. )
  1264.  
  1265. ;;;###autoload
  1266. (defun full-calc-keypad ()
  1267.   "Invoke the Calculator in full-screen \"visual keypad\" mode.
  1268. See calc-keypad for details."
  1269.   (interactive)
  1270.   (calc-extensions)
  1271.   (calc-do-keypad t (interactive-p))
  1272. )
  1273.  
  1274.  
  1275. ;;; Note that modifications to this function may break calc-pass-errors.
  1276. (defun calc-do (do-body &optional do-slow)
  1277.   (calc-check-defines)
  1278.   (let* ((calc-command-flags nil)
  1279.      (calc-start-time (and calc-timing (not calc-start-time)
  1280.                    (calc-extensions)
  1281.                    (current-time-string)))
  1282.      (gc-cons-threshold (max gc-cons-threshold
  1283.                  (if calc-timing 2000000 100000))))
  1284.     (setq calc-aborted-prefix "")
  1285.     (unwind-protect
  1286.     (condition-case err
  1287.         (save-excursion
  1288.           (if calc-embedded-info
  1289.           (calc-embedded-select-buffer)
  1290.         (calc-select-buffer))
  1291.           (and (eq calc-algebraic-mode 'total)
  1292.            (calc-extensions)
  1293.            (use-local-map calc-alg-map))
  1294.           (and do-slow calc-display-working-message
  1295.            (progn
  1296.              (message "Working...")
  1297.              (calc-set-command-flag 'clear-message)))
  1298.           (funcall do-body)
  1299.           (setq calc-aborted-prefix nil)
  1300.           (and (memq 'renum-stack calc-command-flags)
  1301.            (calc-renumber-stack))
  1302.           (and (memq 'clear-message calc-command-flags)
  1303.            (message "")))
  1304.       (error
  1305.        (if (and (eq (car err) 'error)
  1306.             (stringp (nth 1 err))
  1307.             (string-match "max-specpdl-size\\|max-lisp-eval-depth"
  1308.                   (nth 1 err)))
  1309.            (error "Computation got stuck or ran too long.  Type `M' to increase the limit.")
  1310.          (setq calc-aborted-prefix nil)
  1311.          (signal (car err) (cdr err)))))
  1312.       (setq calc-old-aborted-prefix calc-aborted-prefix)
  1313.       (and calc-aborted-prefix
  1314.        (calc-record "<Aborted>" calc-aborted-prefix))
  1315.       (and calc-start-time
  1316.        (let* ((calc-internal-prec 12)
  1317.           (calc-date-format nil)
  1318.           (end-time (current-time-string))
  1319.           (time (if (equal calc-start-time end-time)
  1320.                 0
  1321.               (math-sub
  1322.                (calcFunc-unixtime (math-parse-date end-time) 0)
  1323.                (calcFunc-unixtime (math-parse-date calc-start-time)
  1324.                           0)))))
  1325.          (if (math-lessp 1 time)
  1326.          (calc-record time "(t)"))))
  1327.       (or (memq 'no-align calc-command-flags)
  1328.       (eq major-mode 'calc-trail-mode)
  1329.       (calc-align-stack-window))
  1330.       (and (memq 'position-point calc-command-flags)
  1331.        (if (eq major-mode 'calc-mode)
  1332.            (progn
  1333.          (goto-line calc-final-point-line)
  1334.          (move-to-column calc-final-point-column))
  1335.          (save-excursion
  1336.            (calc-select-buffer)
  1337.            (goto-line calc-final-point-line)
  1338.            (move-to-column calc-final-point-column))))
  1339.       (or (memq 'keep-flags calc-command-flags)
  1340.       (save-excursion
  1341.         (calc-select-buffer)
  1342.         (setq calc-inverse-flag nil
  1343.           calc-hyperbolic-flag nil
  1344.           calc-keep-args-flag nil)))
  1345.       (and (memq 'do-edit calc-command-flags)
  1346.        (switch-to-buffer (get-buffer-create "*Calc Edit*")))
  1347.       (calc-set-mode-line)
  1348.       (and calc-embedded-info
  1349.        (calc-embedded-finish-command))))
  1350.   (identity nil)  ; allow a GC after timing is done
  1351. )
  1352. (setq calc-aborted-prefix nil)
  1353. (setq calc-start-time nil)
  1354.  
  1355. (defun calc-set-command-flag (f)
  1356.   (if (not (memq f calc-command-flags))
  1357.       (setq calc-command-flags (cons f calc-command-flags)))
  1358. )
  1359.  
  1360. (defun calc-select-buffer ()
  1361.   (or (eq major-mode 'calc-mode)
  1362.       (if calc-main-buffer
  1363.       (set-buffer calc-main-buffer)
  1364.     (let ((buf (get-buffer "*Calculator*")))
  1365.       (if buf
  1366.           (set-buffer buf)
  1367.         (error "Calculator buffer not available")))))
  1368. )
  1369.  
  1370. (defun calc-cursor-stack-index (&optional index)
  1371.   (goto-char (point-max))
  1372.   (forward-line (- (calc-substack-height (or index 1))))
  1373. )
  1374.  
  1375. (defun calc-stack-size ()
  1376.   (- (length calc-stack) calc-stack-top)
  1377. )
  1378.  
  1379. (defun calc-substack-height (n)
  1380.   (let ((sum 0)
  1381.     (stack calc-stack))
  1382.     (setq n (+ n calc-stack-top))
  1383.     (while (and (> n 0) stack)
  1384.       (setq sum (+ sum (nth 1 (car stack)))
  1385.         n (1- n)
  1386.         stack (cdr stack)))
  1387.     sum)
  1388. )
  1389.  
  1390. (defun calc-set-mode-line ()
  1391.   (save-excursion
  1392.     (calc-select-buffer)
  1393.     (let* ((fmt (car calc-float-format))
  1394.        (figs (nth 1 calc-float-format))
  1395.        (new-mode-string
  1396.         (format "Calc%s%s: %d %s %-14s"
  1397.             (if calc-embedded-info "Embed" "")
  1398.             (if (and (> (length (buffer-name)) 12)
  1399.                  (equal (substring (buffer-name) 0 12)
  1400.                     "*Calculator*"))
  1401.             (substring (buffer-name) 12)
  1402.               "")
  1403.             calc-internal-prec
  1404.             (capitalize (symbol-name calc-angle-mode))
  1405.             (concat
  1406.  
  1407.              ;; Input-related modes
  1408.              (if (eq calc-algebraic-mode 'total) "Alg* "
  1409.                (if calc-algebraic-mode "Alg "
  1410.              (if calc-incomplete-algebraic-mode "Alg[( " "")))
  1411.  
  1412.              ;; Computational modes
  1413.              (if calc-symbolic-mode "Symb " "")
  1414.              (cond ((eq calc-matrix-mode 'matrix) "Matrix ")
  1415.                ((integerp calc-matrix-mode)
  1416.                 (format "Matrix%d " calc-matrix-mode))
  1417.                ((eq calc-matrix-mode 'scalar) "Scalar ")
  1418.                (t ""))
  1419.              (if (eq calc-complex-mode 'polar) "Polar " "")
  1420.              (if calc-prefer-frac "Frac " "")
  1421.              (cond ((null calc-infinite-mode) "")
  1422.                ((eq calc-infinite-mode 1) "+Inf ")
  1423.                (t "Inf "))
  1424.              (cond ((eq calc-simplify-mode 'none) "NoSimp ")
  1425.                ((eq calc-simplify-mode 'num) "NumSimp ")
  1426.                ((eq calc-simplify-mode 'binary)
  1427.                 (format "BinSimp%d " calc-word-size))
  1428.                ((eq calc-simplify-mode 'alg) "AlgSimp ")
  1429.                ((eq calc-simplify-mode 'ext) "ExtSimp ")
  1430.                ((eq calc-simplify-mode 'units) "UnitSimp ")
  1431.                (t ""))
  1432.  
  1433.              ;; Display modes
  1434.              (cond ((= calc-number-radix 10) "")
  1435.                ((= calc-number-radix 2) "Bin ")
  1436.                ((= calc-number-radix 8) "Oct ")
  1437.                ((= calc-number-radix 16) "Hex ")
  1438.                (t (format "Radix%d " calc-number-radix)))
  1439.              (if calc-leading-zeros "Zero " "")
  1440.              (cond ((null calc-language) "")
  1441.                ((eq calc-language 'tex) "TeX ")
  1442.                (t (concat
  1443.                    (capitalize (symbol-name calc-language))
  1444.                    " ")))
  1445.              (cond ((eq fmt 'float)
  1446.                 (if (zerop figs) "" (format "Norm%d " figs)))
  1447.                ((eq fmt 'fix) (format "Fix%d " figs))
  1448.                ((eq fmt 'sci)
  1449.                 (if (zerop figs) "Sci " (format "Sci%d " figs)))
  1450.                ((eq fmt 'eng)
  1451.                 (if (zerop figs) "Eng " (format "Eng%d " figs))))
  1452.              (cond ((not calc-display-just)
  1453.                 (if calc-display-origin
  1454.                 (format "Left%d " calc-display-origin) ""))
  1455.                ((eq calc-display-just 'right)
  1456.                 (if calc-display-origin
  1457.                 (format "Right%d " calc-display-origin)
  1458.                   "Right "))
  1459.                (t
  1460.                 (if calc-display-origin
  1461.                 (format "Center%d " calc-display-origin)
  1462.                   "Center ")))
  1463.              (cond ((integerp calc-line-breaking)
  1464.                 (format "Wid%d " calc-line-breaking))
  1465.                (calc-line-breaking "")
  1466.                (t "Wide "))
  1467.  
  1468.              ;; Miscellaneous other modes/indicators
  1469.              (if calc-assoc-selections "" "Break ")
  1470.              (cond ((eq calc-mode-save-mode 'save) "Save ")
  1471.                ((not calc-embedded-info) "")
  1472.                ((eq calc-mode-save-mode 'local) "Local ")
  1473.                ((eq calc-mode-save-mode 'edit) "LocEdit ")
  1474.                ((eq calc-mode-save-mode 'perm) "LocPerm ")
  1475.                ((eq calc-mode-save-mode 'global) "Global ")
  1476.                (t ""))
  1477.              (if calc-auto-recompute "" "Manual ")
  1478.              (if (and (fboundp 'calc-gnuplot-alive)
  1479.                   (calc-gnuplot-alive)) "Graph " "")
  1480.              (if (and calc-embedded-info
  1481.                   (> (calc-stack-size) 0)
  1482.                   (calc-top 1 'sel)) "Sel " "")
  1483.              (if calc-display-dirty "Dirty " "")
  1484.              (if calc-inverse-flag "Inv " "")
  1485.              (if calc-hyperbolic-flag "Hyp " "")
  1486.              (if calc-keep-args-flag "Keep " "")
  1487.              (if (/= calc-stack-top 1) "Narrow " "")
  1488.              (apply 'concat calc-other-modes)))))
  1489.       (if (equal new-mode-string mode-line-buffer-identification)
  1490.       nil
  1491.     (setq mode-line-buffer-identification new-mode-string)
  1492.     (set-buffer-modified-p (buffer-modified-p))
  1493.     (and calc-embedded-info (calc-embedded-mode-line-change)))))
  1494. )
  1495.  
  1496. (defun calc-align-stack-window ()
  1497.   (if (eq major-mode 'calc-mode)
  1498.       (progn
  1499.     (let ((win (get-buffer-window (current-buffer))))
  1500.       (if win
  1501.           (progn
  1502.         (calc-cursor-stack-index 0)
  1503.         (vertical-motion (- 2 (window-height win)))
  1504.         (set-window-start win (point)))))
  1505.     (calc-cursor-stack-index 0)
  1506.     (if (looking-at " *\\.$")
  1507.         (goto-char (1- (match-end 0)))))
  1508.     (save-excursion
  1509.       (calc-select-buffer)
  1510.       (calc-align-stack-window)))
  1511. )
  1512.  
  1513. (defun calc-check-stack (n)
  1514.   (if (> n (calc-stack-size))
  1515.       (error "Too few elements on stack"))
  1516.   (if (< n 0)
  1517.       (error "Invalid argument"))
  1518. )
  1519.  
  1520. (defun calc-push-list (vals &optional m sels)
  1521.   (while vals
  1522.     (if calc-executing-macro
  1523.     (calc-push-list-in-macro vals m sels)
  1524.       (save-excursion
  1525.     (calc-select-buffer)
  1526.     (let* ((val (car vals))
  1527.            (entry (list val 1 (car sels)))
  1528.            (mm (+ (or m 1) calc-stack-top)))
  1529.       (calc-cursor-stack-index (1- (or m 1)))
  1530.       (if (> mm 1)
  1531.           (setcdr (nthcdr (- mm 2) calc-stack)
  1532.               (cons entry (nthcdr (1- mm) calc-stack)))
  1533.         (setq calc-stack (cons entry calc-stack)))
  1534.       (let ((buffer-read-only nil))
  1535.         (insert (math-format-stack-value entry) "\n"))
  1536.       (calc-record-undo (list 'push mm))
  1537.       (calc-set-command-flag 'renum-stack))))
  1538.     (setq vals (cdr vals)
  1539.       sels (cdr sels)))
  1540. )
  1541.  
  1542. (defun calc-pop-push-list (n vals &optional m sels)
  1543.   (if (and calc-any-selections (null sels))
  1544.       (calc-replace-selections n vals m)
  1545.     (calc-pop-stack n m sels)
  1546.     (calc-push-list vals m sels))
  1547. )
  1548.  
  1549. (defun calc-pop-push-record-list (n prefix vals &optional m sels)
  1550.   (or (and (consp vals)
  1551.        (or (integerp (car vals))
  1552.            (consp (car vals))))
  1553.       (and vals (setq vals (list vals)
  1554.               sels (and sels (list sels)))))
  1555.   (calc-check-stack (+ n (or m 1) -1))
  1556.   (if prefix
  1557.       (if (cdr vals)
  1558.       (calc-record-list vals prefix)
  1559.     (calc-record (car vals) prefix)))
  1560.   (calc-pop-push-list n vals m sels)
  1561. )
  1562.  
  1563. (defun calc-enter-result (n prefix vals &optional m)
  1564.   (setq calc-aborted-prefix prefix)
  1565.   (if (and (consp vals)
  1566.        (or (integerp (car vals))
  1567.            (consp (car vals))))
  1568.       (setq vals (mapcar 'calc-normalize vals))
  1569.     (setq vals (calc-normalize vals)))
  1570.   (or (and (consp vals)
  1571.        (or (integerp (car vals))
  1572.            (consp (car vals))))
  1573.       (setq vals (list vals)))
  1574.   (if (equal vals '((nil)))
  1575.       (setq vals nil))
  1576.   (calc-pop-push-record-list n prefix vals m)
  1577.   (calc-handle-whys)
  1578. )
  1579.  
  1580. (defun calc-normalize (val)
  1581.   (if (memq calc-simplify-mode '(nil none num))
  1582.       (math-normalize val)
  1583.     (calc-extensions)
  1584.     (calc-normalize-fancy val))
  1585. )
  1586.  
  1587. (defun calc-handle-whys ()
  1588.   (if calc-next-why
  1589.       (calc-do-handle-whys))
  1590. )
  1591.  
  1592.  
  1593. (defun calc-pop-stack (&optional n m sel-ok)  ; pop N objs at level M of stack.
  1594.   (or n (setq n 1))
  1595.   (or m (setq m 1))
  1596.   (or calc-keep-args-flag
  1597.       (let ((mm (+ m calc-stack-top)))
  1598.     (if (and calc-any-selections (not sel-ok)
  1599.          (calc-top-selected n m))
  1600.         (calc-sel-error))
  1601.     (if calc-executing-macro
  1602.         (calc-pop-stack-in-macro n mm)
  1603.       (calc-record-undo (list 'pop mm (calc-top-list n m 'full)))
  1604.       (save-excursion
  1605.         (calc-select-buffer)
  1606.         (let ((buffer-read-only nil))
  1607.           (if (> mm 1)
  1608.           (progn
  1609.             (calc-cursor-stack-index (1- m))
  1610.             (let ((bot (point)))
  1611.               (calc-cursor-stack-index (+ n m -1))
  1612.               (delete-region (point) bot))
  1613.             (setcdr (nthcdr (- mm 2) calc-stack)
  1614.                 (nthcdr (+ n mm -1) calc-stack)))
  1615.         (calc-cursor-stack-index n)
  1616.         (setq calc-stack (nthcdr n calc-stack))
  1617.         (delete-region (point) (point-max))))
  1618.         (calc-set-command-flag 'renum-stack)))))
  1619. )
  1620.  
  1621. (defun calc-get-stack-element (x)
  1622.   (cond ((eq sel-mode 'entry)
  1623.      x)
  1624.     ((eq sel-mode 'sel)
  1625.      (nth 2 x))
  1626.     ((or (null (nth 2 x))
  1627.          (eq sel-mode 'full)
  1628.          (not calc-use-selections))
  1629.      (car x))
  1630.     (sel-mode
  1631.      (calc-sel-error))
  1632.     (t (nth 2 x)))
  1633. )
  1634.  
  1635. ;; Get the Nth element of the stack (N=1 is the top element).
  1636. (defun calc-top (&optional n sel-mode)
  1637.   (or n (setq n 1))
  1638.   (calc-check-stack n)
  1639.   (calc-get-stack-element (nth (+ n calc-stack-top -1) calc-stack))
  1640. )
  1641.  
  1642. (defun calc-top-n (&optional n sel-mode)    ; in case precision has changed
  1643.   (math-check-complete (calc-normalize (calc-top n sel-mode)))
  1644. )
  1645.  
  1646. (defun calc-top-list (&optional n m sel-mode)
  1647.   (or n (setq n 1))
  1648.   (or m (setq m 1))
  1649.   (calc-check-stack (+ n m -1))
  1650.   (and (> n 0)
  1651.        (let ((top (copy-sequence (nthcdr (+ m calc-stack-top -1)
  1652.                      calc-stack))))
  1653.      (setcdr (nthcdr (1- n) top) nil)
  1654.      (nreverse (mapcar 'calc-get-stack-element top))))
  1655. )
  1656.  
  1657. (defun calc-top-list-n (&optional n m sel-mode)
  1658.   (mapcar 'math-check-complete
  1659.       (mapcar 'calc-normalize (calc-top-list n m sel-mode)))
  1660. )
  1661.  
  1662.  
  1663. (defun calc-renumber-stack ()
  1664.   (if calc-line-numbering
  1665.       (save-excursion
  1666.     (calc-cursor-stack-index 0)
  1667.     (let ((lnum 1)
  1668.           (buffer-read-only nil)
  1669.           (stack (nthcdr calc-stack-top calc-stack)))
  1670.       (if (re-search-forward "^[0-9]+[:*]" nil t)
  1671.           (progn
  1672.         (beginning-of-line)
  1673.         (while (re-search-forward "^[0-9]+[:*]" nil t)
  1674.           (let ((buffer-read-only nil))
  1675.             (beginning-of-line)
  1676.             (delete-char 4)
  1677.             (insert "    ")))
  1678.         (calc-cursor-stack-index 0)))
  1679.       (while (re-search-backward "^[0-9]+[:*]" nil t)
  1680.         (delete-char 4)
  1681.         (if (> lnum 999)
  1682.         (insert (format "%03d%s" (% lnum 1000)
  1683.                 (if (and (nth 2 (car stack))
  1684.                      calc-use-selections) "*" ":")))
  1685.           (let ((prefix (int-to-string lnum)))
  1686.         (insert prefix (if (and (nth 2 (car stack))
  1687.                     calc-use-selections) "*" ":")
  1688.             (make-string (- 3 (length prefix)) 32))))
  1689.         (beginning-of-line)
  1690.         (setq lnum (1+ lnum)
  1691.           stack (cdr stack))))))
  1692.   (and calc-embedded-info (calc-embedded-stack-change))
  1693. )
  1694.  
  1695. (defun calc-refresh (&optional align)
  1696.   (interactive)
  1697.   (and (eq major-mode 'calc-mode)
  1698.        (not calc-executing-macro)
  1699.        (let* ((buffer-read-only nil)
  1700.           (save-point (point))
  1701.           (save-mark (condition-case err (mark) (error nil)))
  1702.           (save-aligned (looking-at "\\.$"))
  1703.           (thing calc-stack))
  1704.      (setq calc-any-selections nil
  1705.            calc-any-evaltos nil)
  1706.      (erase-buffer)
  1707.      (insert "--- Emacs Calculator Mode ---\n")
  1708.      (while thing
  1709.        (goto-char (point-min))
  1710.        (forward-line 1)
  1711.        (insert (math-format-stack-value (car thing)) "\n")
  1712.        (setq thing (cdr thing)))
  1713.      (calc-renumber-stack)
  1714.      (if calc-display-dirty
  1715.          (calc-wrapper (setq calc-display-dirty nil)))
  1716.      (and calc-any-evaltos calc-auto-recompute
  1717.           (calc-wrapper (calc-refresh-evaltos)))
  1718.      (if (or align save-aligned)
  1719.          (calc-align-stack-window)
  1720.        (goto-char save-point))
  1721.      (if save-mark (set-mark save-mark))))
  1722.   (and calc-embedded-info (not (eq major-mode 'calc-mode))
  1723.        (save-excursion
  1724.      (set-buffer (aref calc-embedded-info 1))
  1725.      (calc-refresh align)))
  1726.   (setq calc-refresh-count (1+ calc-refresh-count))
  1727. )
  1728.  
  1729.  
  1730. (defun calc-x-paste-text (arg)
  1731.   "Move point to mouse position and insert window system cut buffer contents.
  1732. If mouse is pressed in Calc window, push cut buffer contents onto the stack."
  1733.   (x-mouse-select arg)
  1734.   (if (memq major-mode '(calc-mode calc-trail-mode))
  1735.       (progn
  1736.     (calc-wrapper
  1737.      (calc-extensions)
  1738.      (let* ((buf (x-get-cut-buffer))
  1739.         (val (math-read-exprs (calc-clean-newlines buf))))
  1740.        (if (eq (car-safe val) 'error)
  1741.            (progn
  1742.          (setq val (math-read-exprs buf))
  1743.          (if (eq (car-safe val) 'error)
  1744.              (error "%s in yanked data" (nth 2 val)))))
  1745.        (calc-enter-result 0 "Xynk" val))))
  1746.     (x-paste-text arg))
  1747. )
  1748.  
  1749.  
  1750.  
  1751. ;;;; The Calc Trail buffer.
  1752.  
  1753. (defun calc-check-trail-aligned ()
  1754.   (save-excursion
  1755.     (let ((win (get-buffer-window (current-buffer))))
  1756.       (and win
  1757.        (pos-visible-in-window-p (1- (point-max)) win))))
  1758. )
  1759.  
  1760. (defun calc-trail-buffer ()
  1761.   (and (or (null calc-trail-buffer)
  1762.        (null (buffer-name calc-trail-buffer)))
  1763.        (save-excursion
  1764.      (setq calc-trail-buffer (get-buffer-create "*Calc Trail*"))
  1765.      (let ((buf (or (and (not (eq major-mode 'calc-mode))
  1766.                  (get-buffer "*Calculator*"))
  1767.             (current-buffer))))
  1768.        (set-buffer calc-trail-buffer)
  1769.        (or (eq major-mode 'calc-trail-mode)
  1770.            (calc-trail-mode buf)))))
  1771.   (or (and calc-trail-pointer
  1772.        (eq (marker-buffer calc-trail-pointer) calc-trail-buffer))
  1773.       (save-excursion
  1774.     (set-buffer calc-trail-buffer)
  1775.     (goto-line 2)
  1776.     (setq calc-trail-pointer (point-marker))))
  1777.   calc-trail-buffer
  1778. )
  1779.  
  1780. (defun calc-record (val &optional prefix)
  1781.   (setq calc-aborted-prefix nil)
  1782.   (or calc-executing-macro
  1783.       (let* ((mainbuf (current-buffer))
  1784.          (buf (calc-trail-buffer))
  1785.          (calc-display-raw nil)
  1786.          (calc-can-abbrev-vectors t)
  1787.          (fval (if val
  1788.                (if (stringp val)
  1789.                val
  1790.              (math-showing-full-precision
  1791.               (math-format-flat-expr val 0)))
  1792.              "")))
  1793.     (save-excursion
  1794.       (set-buffer buf)
  1795.       (let ((aligned (calc-check-trail-aligned))
  1796.         (buffer-read-only nil))
  1797.         (goto-char (point-max))
  1798.         (cond ((null prefix) (insert "     "))
  1799.           ((and (> (length prefix) 4)
  1800.             (string-match " " prefix 4))
  1801.            (insert (substring prefix 0 4) " "))
  1802.           (t (insert (format "%4s " prefix))))
  1803.         (insert fval "\n")
  1804.         (let ((win (get-buffer-window buf)))
  1805.           (if (and aligned win (not (memq 'hold-trail calc-command-flags)))
  1806.           (calc-trail-here))
  1807.           (goto-char (1- (point-max))))))))
  1808.   val
  1809. )
  1810.  
  1811.  
  1812. (defun calc-trail-display (flag &optional no-refresh)
  1813.   (interactive "P")
  1814.   (let ((win (get-buffer-window (calc-trail-buffer))))
  1815.     (if (setq calc-display-trail
  1816.           (not (if flag (memq flag '(nil 0)) win)))
  1817.     (if (null win)
  1818.         (progn
  1819.           (if (and (boundp 'calc-trail-window-hook) calc-trail-window-hook)
  1820.           (run-hooks 'calc-trail-window-hook)
  1821.         (let ((w (split-window nil (/ (* (window-width) 2) 3) t)))
  1822.           (set-window-buffer w calc-trail-buffer)))
  1823.           (calc-wrapper
  1824.            (setq overlay-arrow-string calc-trail-overlay
  1825.              overlay-arrow-position calc-trail-pointer)
  1826.            (or no-refresh
  1827.            (if (interactive-p)
  1828.                (calc-do-refresh)
  1829.              (calc-refresh))))))
  1830.       (if win
  1831.       (progn
  1832.         (delete-window win)
  1833.         (calc-wrapper
  1834.          (or no-refresh
  1835.          (if (interactive-p)
  1836.              (calc-do-refresh)
  1837.            (calc-refresh))))))))
  1838.   calc-trail-buffer
  1839. )
  1840.  
  1841. (defun calc-trail-here ()
  1842.   (interactive)
  1843.   (if (eq major-mode 'calc-trail-mode)
  1844.       (progn
  1845.     (beginning-of-line)
  1846.     (if (bobp)
  1847.         (forward-line 1)
  1848.       (if (eobp)
  1849.           (forward-line -1)))
  1850.     (if (or (bobp) (eobp))
  1851.         (setq overlay-arrow-position nil)   ; trail is empty
  1852.       (set-marker calc-trail-pointer (point) (current-buffer))
  1853.       (setq calc-trail-overlay (concat (buffer-substring (point)
  1854.                                  (+ (point) 4))
  1855.                        ">")
  1856.         overlay-arrow-string calc-trail-overlay
  1857.         overlay-arrow-position calc-trail-pointer)
  1858.       (forward-char 4)
  1859.       (let ((win (get-buffer-window (current-buffer))))
  1860.         (if win
  1861.         (save-excursion
  1862.           (forward-line (/ (window-height win) 2))
  1863.           (forward-line (- 1 (window-height win)))
  1864.           (set-window-start win (point))
  1865.           (set-window-point win (+ calc-trail-pointer 4))
  1866.           (set-buffer calc-main-buffer)
  1867.           (setq overlay-arrow-string calc-trail-overlay
  1868.             overlay-arrow-position calc-trail-pointer))))))
  1869.     (error "Not in Calc Trail buffer"))
  1870. )
  1871.  
  1872.  
  1873.  
  1874.  
  1875. ;;;; The Undo list.
  1876.  
  1877. (defun calc-record-undo (rec)
  1878.   (or calc-executing-macro
  1879.       (if (memq 'undo calc-command-flags)
  1880.       (setq calc-undo-list (cons (cons rec (car calc-undo-list))
  1881.                      (cdr calc-undo-list)))
  1882.     (setq calc-undo-list (cons (list rec) calc-undo-list)
  1883.           calc-redo-list nil)
  1884.     (calc-set-command-flag 'undo)))
  1885. )
  1886.  
  1887.  
  1888.  
  1889.  
  1890. ;;; Arithmetic commands.
  1891.  
  1892. (defun calc-binary-op (name func arg &optional ident unary func2)
  1893.   (setq calc-aborted-prefix name)
  1894.   (if (null arg)
  1895.       (calc-enter-result 2 name (cons (or func2 func)
  1896.                       (mapcar 'math-check-complete
  1897.                           (calc-top-list 2))))
  1898.     (calc-extensions)
  1899.     (calc-binary-op-fancy name func arg ident unary))
  1900. )
  1901.  
  1902. (defun calc-unary-op (name func arg &optional func2)
  1903.   (setq calc-aborted-prefix name)
  1904.   (if (null arg)
  1905.       (calc-enter-result 1 name (list (or func2 func)
  1906.                       (math-check-complete (calc-top 1))))
  1907.     (calc-extensions)
  1908.     (calc-unary-op-fancy name func arg))
  1909. )
  1910.  
  1911.  
  1912. (defun calc-plus (arg)
  1913.   (interactive "P")
  1914.   (calc-slow-wrapper
  1915.    (calc-binary-op "+" 'calcFunc-add arg 0 nil '+))
  1916. )
  1917.  
  1918. (defun calc-minus (arg)
  1919.   (interactive "P")
  1920.   (calc-slow-wrapper
  1921.    (calc-binary-op "-" 'calcFunc-sub arg 0 'neg '-))
  1922. )
  1923.  
  1924. (defun calc-times (arg)
  1925.   (interactive "P")
  1926.   (calc-slow-wrapper
  1927.    (calc-binary-op "*" 'calcFunc-mul arg 1 nil '*))
  1928. )
  1929.  
  1930. (defun calc-divide (arg)
  1931.   (interactive "P")
  1932.   (calc-slow-wrapper
  1933.    (calc-binary-op "/" 'calcFunc-div arg 0 'calcFunc-inv '/))
  1934. )
  1935.  
  1936.  
  1937. (defun calc-change-sign (arg)
  1938.   (interactive "P")
  1939.   (calc-wrapper
  1940.    (calc-unary-op "chs" 'neg arg))
  1941. )
  1942.  
  1943.  
  1944.  
  1945. ;;; Stack management commands.
  1946.  
  1947. (defun calc-enter (n)
  1948.   (interactive "p")
  1949.   (calc-wrapper
  1950.    (cond ((< n 0)
  1951.       (calc-push-list (calc-top-list 1 (- n))))
  1952.      ((= n 0)
  1953.       (calc-push-list (calc-top-list (calc-stack-size))))
  1954.      (t
  1955.       (calc-push-list (calc-top-list n)))))
  1956. )
  1957.  
  1958.  
  1959. (defun calc-pop (n)
  1960.   (interactive "P")
  1961.   (calc-wrapper
  1962.    (let* ((nn (prefix-numeric-value n))
  1963.       (top (and (null n) (calc-top 1))))
  1964.      (cond ((and (null n)
  1965.          (eq (car-safe top) 'incomplete)
  1966.          (> (length top) (if (eq (nth 1 top) 'intv) 3 2)))
  1967.         (calc-pop-push-list 1 (let ((tt (copy-sequence top)))
  1968.                     (setcdr (nthcdr (- (length tt) 2) tt) nil)
  1969.                     (list tt))))
  1970.        ((< nn 0)
  1971.         (if (and calc-any-selections
  1972.              (calc-top-selected 1 (- nn)))
  1973.         (calc-delete-selection (- nn))
  1974.           (calc-pop-stack 1 (- nn) t)))
  1975.        ((= nn 0)
  1976.         (calc-pop-stack (calc-stack-size) 1 t))
  1977.        (t
  1978.         (if (and calc-any-selections
  1979.              (= nn 1)
  1980.              (calc-top-selected 1 1))
  1981.         (calc-delete-selection 1)
  1982.           (calc-pop-stack nn))))))
  1983. )
  1984.  
  1985.  
  1986.  
  1987.  
  1988. ;;;; Reading a number using the minibuffer.
  1989.  
  1990. (defun calcDigit-start ()
  1991.   (interactive)
  1992.   (calc-wrapper
  1993.    (if (or calc-algebraic-mode
  1994.        (and (> calc-number-radix 14) (eq last-command-char ?e)))
  1995.        (calc-alg-digit-entry)
  1996.      (setq unread-command-char last-command-char
  1997.        calc-aborted-prefix nil)
  1998.      (let* ((calc-digit-value nil)
  1999.         (calc-prev-char nil)
  2000.         (calc-prev-prev-char nil)
  2001.         (calc-buffer (current-buffer))
  2002.         (old-esc (lookup-key global-map "\e"))
  2003.         (buf (unwind-protect
  2004.              (progn
  2005.                (define-key global-map "\e" nil)
  2006.                (read-from-minibuffer "Calc: " "" calc-digit-map))
  2007.            (define-key global-map "\e" old-esc))))
  2008.        (or calc-digit-value (setq calc-digit-value (math-read-number buf)))
  2009.        (if (stringp calc-digit-value)
  2010.        (calc-alg-entry calc-digit-value)
  2011.      (if calc-digit-value
  2012.          (calc-push-list (list (calc-record (calc-normalize
  2013.                          calc-digit-value))))))
  2014.        (if (eq calc-prev-char 'dots)
  2015.        (progn
  2016.          (calc-extensions)
  2017.          (calc-dots))))))
  2018. )
  2019.  
  2020. (defun calcDigit-nondigit ()
  2021.   (interactive)
  2022.   ;; Exercise for the reader:  Figure out why this is a good precaution!
  2023.   (or (boundp 'calc-buffer)
  2024.       (use-local-map minibuffer-local-map))
  2025.   (let ((str (buffer-string)))
  2026.     (setq calc-digit-value (save-excursion
  2027.                  (set-buffer calc-buffer)
  2028.                  (math-read-number str))))
  2029.   (if (and (null calc-digit-value) (> (buffer-size) 0))
  2030.       (progn
  2031.     (beep)
  2032.     (calc-temp-minibuffer-message " [Bad format]"))
  2033.     (or (memq last-command-char '(32 13))
  2034.     (setq prefix-arg current-prefix-arg
  2035.           unread-command-char (if (and (eq last-command-char 27)
  2036.                        (>= last-input-char 128))
  2037.                       last-input-char
  2038.                     last-command-char)))
  2039.     (exit-minibuffer))
  2040. )
  2041.  
  2042.  
  2043. (defun calc-minibuffer-contains (rex)
  2044.   (save-excursion
  2045.     (goto-char (point-min))
  2046.     (looking-at rex))
  2047. )
  2048.  
  2049. (defun calcDigit-key ()
  2050.   (interactive)
  2051.   (goto-char (point-max))
  2052.   (if (or (and (memq last-command-char '(?+ ?-))
  2053.            (> (buffer-size) 0)
  2054.            (/= (preceding-char) ?e))
  2055.       (and (memq last-command-char '(?m ?s))
  2056.            (not (calc-minibuffer-contains "[-+]?[0-9]+\\.?0*[@oh].*"))
  2057.            (not (calc-minibuffer-contains "[-+]?\\(1[1-9]\\|[2-9][0-9]\\)#.*"))))
  2058.       (calcDigit-nondigit)
  2059.     (if (calc-minibuffer-contains "\\([-+]?\\|.* \\)\\'")
  2060.     (cond ((memq last-command-char '(?. ?@)) (insert "0"))
  2061.           ((and (memq last-command-char '(?o ?h ?m))
  2062.             (not (calc-minibuffer-contains ".*#.*"))) (insert "0"))
  2063.           ((memq last-command-char '(?: ?e)) (insert "1"))
  2064.           ((eq last-command-char ?#)
  2065.            (insert (int-to-string calc-number-radix)))))
  2066.     (if (and (calc-minibuffer-contains "\\([-+]?[0-9]+#\\|[^:]*:\\)\\'")
  2067.          (eq last-command-char ?:))
  2068.     (insert "1"))
  2069.     (if (and (calc-minibuffer-contains "[-+]?[0-9]+#\\'")
  2070.          (eq last-command-char ?.))
  2071.     (insert "0"))
  2072.     (if (and (calc-minibuffer-contains "[-+]?0*\\([2-9]\\|1[0-4]\\)#\\'")
  2073.          (eq last-command-char ?e))
  2074.     (insert "1"))
  2075.     (if (or (and (memq last-command-char '(?h ?o ?m ?s ?p))
  2076.          (calc-minibuffer-contains ".*#.*"))
  2077.         (and (eq last-command-char ?e)
  2078.          (calc-minibuffer-contains "[-+]?\\(1[5-9]\\|[2-9][0-9]\\)#.*"))
  2079.         (and (eq last-command-char ?n)
  2080.          (calc-minibuffer-contains "[-+]?\\(2[4-9]\\|[3-9][0-9]\\)#.*")))
  2081.     (setq last-command-char (upcase last-command-char)))
  2082.     (cond
  2083.      ((memq last-command-char '(?_ ?n))
  2084.       (goto-char (point-min))
  2085.       (if (and (search-forward " +/- " nil t)
  2086.            (not (search-forward "e" nil t)))
  2087.       (beep)
  2088.     (and (not (calc-minibuffer-contains "[-+]?\\(1[5-9]\\|[2-9][0-9]\\)#.*"))
  2089.          (search-forward "e" nil t))
  2090.     (if (looking-at "+")
  2091.         (delete-char 1))
  2092.     (if (looking-at "-")
  2093.         (delete-char 1)
  2094.       (insert "-")))
  2095.       (goto-char (point-max)))
  2096.      ((eq last-command-char ?p)
  2097.       (if (or (calc-minibuffer-contains ".*\\+/-.*")
  2098.           (calc-minibuffer-contains ".*mod.*")
  2099.           (calc-minibuffer-contains ".*#.*")
  2100.           (calc-minibuffer-contains ".*[-+e:]\\'"))
  2101.       (beep)
  2102.     (if (not (calc-minibuffer-contains ".* \\'"))
  2103.         (insert " "))
  2104.     (insert "+/- ")))
  2105.      ((and (eq last-command-char ?M)
  2106.        (not (calc-minibuffer-contains
  2107.          "[-+]?\\(2[3-9]\\|[3-9][0-9]\\)#.*")))
  2108.       (if (or (calc-minibuffer-contains ".*\\+/-.*")
  2109.           (calc-minibuffer-contains ".*mod *[^ ]+")
  2110.           (calc-minibuffer-contains ".*[-+e:]\\'"))
  2111.       (beep)
  2112.     (if (calc-minibuffer-contains ".*mod \\'")
  2113.         (if calc-previous-modulo
  2114.         (insert (math-format-flat-expr calc-previous-modulo 0))
  2115.           (beep))
  2116.       (if (not (calc-minibuffer-contains ".* \\'"))
  2117.           (insert " "))
  2118.       (insert "mod "))))
  2119.      (t
  2120.       (insert (char-to-string last-command-char))
  2121.       (if (or (and (calc-minibuffer-contains "[-+]?\\(.*\\+/- *\\|.*mod *\\)?\\([0-9][0-9]?\\)#[0-9a-zA-Z]*\\(:[0-9a-zA-Z]*\\(:[0-9a-zA-Z]*\\)?\\|.[0-9a-zA-Z]*\\(e[-+]?[0-9]*\\)?\\)?\\'")
  2122.            (let ((radix (string-to-int
  2123.                  (buffer-substring
  2124.                   (match-beginning 2) (match-end 2)))))
  2125.              (and (>= radix 2)
  2126.               (<= radix 36)
  2127.               (or (memq last-command-char '(?# ?: ?. ?e ?+ ?-))
  2128.                   (let ((dig (math-read-radix-digit
  2129.                       (upcase last-command-char))))
  2130.                 (and dig
  2131.                      (< dig radix)))))))
  2132.           (save-excursion
  2133.         (goto-char (point-min))
  2134.              (looking-at
  2135.          "[-+]?\\(.*\\+/- *\\|.*mod *\\)?\\([0-9]+\\.?0*[@oh] *\\)?\\([0-9]+\\.?0*['m] *\\)?[0-9]*\\(\\.?[0-9]*\\(e[-+]?[0-3]?[0-9]?[0-9]?[0-9]?[0-9]?[0-9]?[0-9]?\\)?\\|[0-9]:\\([0-9]+:\\)?[0-9]*\\)?[\"s]?\\'")))
  2136.       (if (and (memq last-command-char '(?@ ?o ?h ?\' ?m))
  2137.            (string-match " " calc-hms-format))
  2138.           (insert " "))
  2139.     (if (and (eq this-command last-command)
  2140.          (eq last-command-char ?.))
  2141.         (progn
  2142.           (calc-extensions)
  2143.           (calc-digit-dots))
  2144.       (delete-backward-char 1)
  2145.       (beep)
  2146.       (calc-temp-minibuffer-message " [Bad format]"))))))
  2147.   (setq calc-prev-prev-char calc-prev-char
  2148.     calc-prev-char last-command-char)
  2149. )
  2150.  
  2151.  
  2152. (defun calcDigit-backspace ()
  2153.   (interactive)
  2154.   (goto-char (point-max))
  2155.   (cond ((calc-minibuffer-contains ".* \\+/- \\'")
  2156.      (backward-delete-char 5))
  2157.     ((calc-minibuffer-contains ".* mod \\'")
  2158.      (backward-delete-char 5))
  2159.     ((calc-minibuffer-contains ".* \\'")
  2160.      (backward-delete-char 2))
  2161.     ((eq last-command 'calcDigit-start)
  2162.      (erase-buffer))
  2163.     (t (backward-delete-char 1)))
  2164.   (if (= (buffer-size) 0)
  2165.       (progn
  2166.     (setq last-command-char 13)
  2167.     (calcDigit-nondigit)))
  2168. )
  2169.  
  2170.  
  2171.  
  2172.  
  2173.  
  2174.  
  2175.  
  2176. ;;;; Arithmetic routines.
  2177. ;;;
  2178. ;;; An object as manipulated by one of these routines may take any of the
  2179. ;;; following forms:
  2180. ;;;
  2181. ;;; integer                 An integer.  For normalized numbers, this format
  2182. ;;;                is used only for -999999 ... 999999.
  2183. ;;;
  2184. ;;; (bigpos N0 N1 N2 ...)   A big positive integer, N0 + N1*1000 + N2*10^6 ...
  2185. ;;; (bigneg N0 N1 N2 ...)   A big negative integer, - N0 - N1*1000 ...
  2186. ;;;                Each digit N is in the range 0 ... 999.
  2187. ;;;                Normalized, always at least three N present,
  2188. ;;;                and the most significant N is nonzero.
  2189. ;;;
  2190. ;;; (frac NUM DEN)          A fraction.  NUM and DEN are small or big integers.
  2191. ;;;                         Normalized, DEN > 1.
  2192. ;;;
  2193. ;;; (float NUM EXP)         A floating-point number, NUM * 10^EXP;
  2194. ;;;                         NUM is a small or big integer, EXP is a small int.
  2195. ;;;                Normalized, NUM is not a multiple of 10, and
  2196. ;;;                abs(NUM) < 10^calc-internal-prec.
  2197. ;;;                Normalized zero is stored as (float 0 0).
  2198. ;;;
  2199. ;;; (cplx REAL IMAG)        A complex number; REAL and IMAG are any of above.
  2200. ;;;                Normalized, IMAG is nonzero.
  2201. ;;;
  2202. ;;; (polar R THETA)         Polar complex number.  Normalized, R > 0 and THETA
  2203. ;;;                         is neither zero nor 180 degrees (pi radians).
  2204. ;;;
  2205. ;;; (vec A B C ...)         Vector of objects A, B, C, ...  A matrix is a
  2206. ;;;                         vector of vectors.
  2207. ;;;
  2208. ;;; (hms H M S)             Angle in hours-minutes-seconds form.  All three
  2209. ;;;                         components have the same sign; H and M must be
  2210. ;;;                         numerically integers; M and S are expected to
  2211. ;;;                         lie in the range [0,60).
  2212. ;;;
  2213. ;;; (date N)                A date or date/time object.  N is an integer to
  2214. ;;;                store a date only, or a fraction or float to
  2215. ;;;                store a date and time.
  2216. ;;;
  2217. ;;; (sdev X SIGMA)          Error form, X +/- SIGMA.  When normalized,
  2218. ;;;                         SIGMA > 0.  X is any complex number and SIGMA
  2219. ;;;                is real numbers; or these may be symbolic
  2220. ;;;                         expressions where SIGMA is assumed real.
  2221. ;;;
  2222. ;;; (intv MASK LO HI)       Interval form.  MASK is 0=(), 1=(], 2=[), or 3=[].
  2223. ;;;                         LO and HI are any real numbers, or symbolic
  2224. ;;;                expressions which are assumed real, and LO < HI.
  2225. ;;;                For [LO..HI], if LO = HI normalization produces LO,
  2226. ;;;                and if LO > HI normalization produces [LO..LO).
  2227. ;;;                For other intervals, if LO > HI normalization
  2228. ;;;                sets HI equal to LO.
  2229. ;;;
  2230. ;;; (mod N M)                Number modulo M.  When normalized, 0 <= N < M.
  2231. ;;;                N and M are real numbers.
  2232. ;;;
  2233. ;;; (var V S)            Symbolic variable.  V is a Lisp symbol which
  2234. ;;;                represents the variable's visible name.  S is
  2235. ;;;                the symbol which actually stores the variable's
  2236. ;;;                value:  (var pi var-pi).
  2237. ;;;
  2238. ;;; In general, combining rational numbers in a calculation always produces
  2239. ;;; a rational result, but if either argument is a float, result is a float.
  2240.  
  2241. ;;; In the following comments, [x y z] means result is x, args must be y, z,
  2242. ;;; respectively, where the code letters are:
  2243. ;;;
  2244. ;;;    O  Normalized object (vector or number)
  2245. ;;;    V  Normalized vector
  2246. ;;;    N  Normalized number of any type
  2247. ;;;    N  Normalized complex number
  2248. ;;;    R  Normalized real number (float or rational)
  2249. ;;;    F  Normalized floating-point number
  2250. ;;;    T  Normalized rational number
  2251. ;;;    I  Normalized integer
  2252. ;;;    B  Normalized big integer
  2253. ;;;    S  Normalized small integer
  2254. ;;;    D  Digit (small integer, 0..999)
  2255. ;;;    L  Normalized bignum digit list (without "bigpos" or "bigneg" symbol)
  2256. ;;;       or normalized vector element list (without "vec")
  2257. ;;;    P  Predicate (truth value)
  2258. ;;;    X  Any Lisp object
  2259. ;;;    Z  "nil"
  2260. ;;;
  2261. ;;; Lower-case letters signify possibly un-normalized values.
  2262. ;;; "L.D" means a cons of an L and a D.
  2263. ;;; [N N; n n] means result will be normalized if argument is.
  2264. ;;; Also, [Public] marks routines intended to be called from outside.
  2265. ;;; [This notation has been neglected in many recent routines.]
  2266.  
  2267. ;;; Reduce an object to canonical (normalized) form.  [O o; Z Z] [Public]
  2268. (defun math-normalize (a)
  2269.   (cond
  2270.    ((not (consp a))
  2271.     (if (integerp a)
  2272.     (if (or (>= a 1000000) (<= a -1000000))
  2273.         (math-bignum a)
  2274.       a)
  2275.       a))
  2276.    ((eq (car a) 'bigpos)
  2277.     (if (eq (nth (1- (length a)) a) 0)
  2278.     (let* ((last (setq a (copy-sequence a))) (digs a))
  2279.       (while (setq digs (cdr digs))
  2280.         (or (eq (car digs) 0) (setq last digs)))
  2281.       (setcdr last nil)))
  2282.     (if (cdr (cdr (cdr a)))
  2283.     a
  2284.       (cond
  2285.        ((cdr (cdr a)) (+ (nth 1 a) (* (nth 2 a) 1000)))
  2286.        ((cdr a) (nth 1 a))
  2287.        (t 0))))
  2288.    ((eq (car a) 'bigneg)
  2289.     (if (eq (nth (1- (length a)) a) 0)
  2290.     (let* ((last (setq a (copy-sequence a))) (digs a))
  2291.       (while (setq digs (cdr digs))
  2292.         (or (eq (car digs) 0) (setq last digs)))
  2293.       (setcdr last nil)))
  2294.     (if (cdr (cdr (cdr a)))
  2295.     a
  2296.       (cond
  2297.        ((cdr (cdr a)) (- (+ (nth 1 a) (* (nth 2 a) 1000))))
  2298.        ((cdr a) (- (nth 1 a)))
  2299.        (t 0))))
  2300.    ((eq (car a) 'float)
  2301.     (math-make-float (math-normalize (nth 1 a)) (nth 2 a)))
  2302.    ((or (memq (car a) '(frac cplx polar hms date mod sdev intv vec var quote
  2303.                  special-const calcFunc-if calcFunc-lambda
  2304.                  calcFunc-quote calcFunc-condition
  2305.                  calcFunc-evalto))
  2306.     (integerp (car a))
  2307.     (and (consp (car a)) (not (eq (car (car a)) 'lambda))))
  2308.     (calc-extensions)
  2309.     (math-normalize-fancy a))
  2310.    (t
  2311.     (or (and calc-simplify-mode
  2312.          (calc-extensions)
  2313.          (math-normalize-nonstandard))
  2314.     (let ((args (mapcar 'math-normalize (cdr a))))
  2315.       (or (condition-case err
  2316.           (let ((func (assq (car a) '( ( + . math-add )
  2317.                            ( - . math-sub )
  2318.                            ( * . math-mul )
  2319.                            ( / . math-div )
  2320.                            ( % . math-mod )
  2321.                            ( ^ . math-pow )
  2322.                            ( neg . math-neg )
  2323.                            ( | . math-concat ) ))))
  2324.             (or (and var-EvalRules
  2325.                  (progn
  2326.                    (or (eq var-EvalRules math-eval-rules-cache-tag)
  2327.                    (progn
  2328.                      (calc-extensions)
  2329.                      (math-recompile-eval-rules)))
  2330.                    (and (or math-eval-rules-cache-other
  2331.                     (assq (car a) math-eval-rules-cache))
  2332.                     (math-apply-rewrites
  2333.                      (cons (car a) args)
  2334.                      (cdr math-eval-rules-cache)
  2335.                      nil math-eval-rules-cache))))
  2336.             (if func
  2337.                 (apply (cdr func) args)
  2338.               (and (or (consp (car a))
  2339.                    (fboundp (car a))
  2340.                    (and (not calc-extensions-loaded)
  2341.                     (calc-extensions)
  2342.                     (fboundp (car a))))
  2343.                    (apply (car a) args)))))
  2344.         (wrong-number-of-arguments
  2345.          (calc-record-why "*Wrong number of arguments"
  2346.                   (cons (car a) args))
  2347.          nil)
  2348.         (wrong-type-argument
  2349.          (or calc-next-why (calc-record-why "Wrong type of argument"
  2350.                             (cons (car a) args)))
  2351.          nil)
  2352.         (args-out-of-range
  2353.          (calc-record-why "*Argument out of range" (cons (car a) args))
  2354.          nil)
  2355.         (inexact-result
  2356.          (calc-record-why "No exact representation for result"
  2357.                   (cons (car a) args))
  2358.          nil)
  2359.         (math-overflow
  2360.          (calc-record-why "*Floating-point overflow occurred"
  2361.                   (cons (car a) args))
  2362.          nil)
  2363.         (math-underflow
  2364.          (calc-record-why "*Floating-point underflow occurred"
  2365.                   (cons (car a) args))
  2366.          nil)
  2367.         (void-variable
  2368.          (if (eq (nth 1 err) 'var-EvalRules)
  2369.              (progn
  2370.                (setq var-EvalRules nil)
  2371.                (math-normalize (cons (car a) args)))
  2372.            (calc-record-why "*Variable is void" (nth 1 err)))))
  2373.           (if (consp (car a))
  2374.           (math-dimension-error)
  2375.         (cons (car a) args)))))))
  2376. )
  2377.  
  2378.  
  2379.  
  2380. ;;; True if A is a floating-point real or complex number.  [P x] [Public]
  2381. (defun math-floatp (a)
  2382.   (cond ((eq (car-safe a) 'float) t)
  2383.     ((memq (car-safe a) '(cplx polar mod sdev intv))
  2384.      (or (math-floatp (nth 1 a))
  2385.          (math-floatp (nth 2 a))
  2386.          (and (eq (car a) 'intv) (math-floatp (nth 3 a)))))
  2387.     ((eq (car-safe a) 'date)
  2388.      (math-floatp (nth 1 a))))
  2389. )
  2390.  
  2391.  
  2392.  
  2393. ;;; Verify that A is a complete object and return A.  [x x] [Public]
  2394. (defun math-check-complete (a)
  2395.   (cond ((integerp a) a)
  2396.     ((eq (car-safe a) 'incomplete)
  2397.      (calc-incomplete-error a))
  2398.     ((consp a) a)
  2399.     (t (error "Invalid data object encountered")))
  2400. )
  2401.  
  2402.  
  2403.  
  2404. ;;; Coerce integer A to be a bignum.  [B S]
  2405. (defun math-bignum (a)
  2406.   (if (>= a 0)
  2407.       (cons 'bigpos (math-bignum-big a))
  2408.     (cons 'bigneg (math-bignum-big (- a))))
  2409. )
  2410.  
  2411. (defun math-bignum-big (a)   ; [L s]
  2412.   (if (= a 0)
  2413.       nil
  2414.     (cons (% a 1000) (math-bignum-big (/ a 1000))))
  2415. )
  2416.  
  2417.  
  2418. ;;; Build a normalized floating-point number.  [F I S]
  2419. (defun math-make-float (mant exp)
  2420.   (if (eq mant 0)
  2421.       '(float 0 0)
  2422.     (let* ((ldiff (- calc-internal-prec (math-numdigs mant))))
  2423.       (if (< ldiff 0)
  2424.       (setq mant (math-scale-rounding mant ldiff)
  2425.         exp (- exp ldiff))))
  2426.     (if (consp mant)
  2427.     (let ((digs (cdr mant)))
  2428.       (if (= (% (car digs) 10) 0)
  2429.           (progn
  2430.         (while (= (car digs) 0)
  2431.           (setq digs (cdr digs)
  2432.             exp (+ exp 3)))
  2433.         (while (= (% (car digs) 10) 0)
  2434.           (setq digs (math-div10-bignum digs)
  2435.             exp (1+ exp)))
  2436.         (setq mant (math-normalize (cons (car mant) digs))))))
  2437.       (while (= (% mant 10) 0)
  2438.     (setq mant (/ mant 10)
  2439.           exp (1+ exp))))
  2440.     (if (and (<= exp -4000000)
  2441.          (<= (+ exp (math-numdigs mant) -1) -4000000))
  2442.     (signal 'math-underflow nil)
  2443.       (if (and (>= exp 3000000)
  2444.            (>= (+ exp (math-numdigs mant) -1) 4000000))
  2445.       (signal 'math-overflow nil)
  2446.     (list 'float mant exp))))
  2447. )
  2448.  
  2449. (defun math-div10-bignum (a)   ; [l l]
  2450.   (if (cdr a)
  2451.       (cons (+ (/ (car a) 10) (* (% (nth 1 a) 10) 100))
  2452.         (math-div10-bignum (cdr a)))
  2453.     (list (/ (car a) 10)))
  2454. )
  2455.  
  2456. ;;; Coerce A to be a float.  [F N; V V] [Public]
  2457. (defun math-float (a)
  2458.   (cond ((Math-integerp a) (math-make-float a 0))
  2459.     ((eq (car a) 'frac) (math-div (math-float (nth 1 a)) (nth 2 a)))
  2460.     ((eq (car a) 'float) a)
  2461.     ((memq (car a) '(cplx polar vec hms date sdev mod))
  2462.      (cons (car a) (mapcar 'math-float (cdr a))))
  2463.     (t (math-float-fancy a)))
  2464. )
  2465.  
  2466.  
  2467. (defun math-neg (a)
  2468.   (cond ((not (consp a)) (- a))
  2469.     ((eq (car a) 'bigpos) (cons 'bigneg (cdr a)))
  2470.     ((eq (car a) 'bigneg) (cons 'bigpos (cdr a)))
  2471.     ((memq (car a) '(frac float))
  2472.      (list (car a) (Math-integer-neg (nth 1 a)) (nth 2 a)))
  2473.     ((memq (car a) '(cplx vec hms date calcFunc-idn))
  2474.      (cons (car a) (mapcar 'math-neg (cdr a))))
  2475.     (t (math-neg-fancy a)))
  2476. )
  2477.  
  2478.  
  2479. ;;; Compute the number of decimal digits in integer A.  [S I]
  2480. (defun math-numdigs (a)
  2481.   (if (consp a)
  2482.       (if (cdr a)
  2483.       (let* ((len (1- (length a)))
  2484.          (top (nth len a)))
  2485.         (+ (* len 3) (cond ((>= top 100) 0) ((>= top 10) -1) (t -2))))
  2486.     0)
  2487.     (cond ((>= a 100) (+ (math-numdigs (/ a 1000)) 3))
  2488.       ((>= a 10) 2)
  2489.       ((>= a 1) 1)
  2490.       ((= a 0) 0)
  2491.       ((> a -10) 1)
  2492.       ((> a -100) 2)
  2493.       (t (math-numdigs (- a)))))
  2494. )
  2495.  
  2496. ;;; Multiply (with truncation toward 0) the integer A by 10^N.  [I i S]
  2497. (defun math-scale-int (a n)
  2498.   (cond ((= n 0) a)
  2499.     ((> n 0) (math-scale-left a n))
  2500.     (t (math-normalize (math-scale-right a (- n)))))
  2501. )
  2502.  
  2503. (defun math-scale-left (a n)   ; [I I S]
  2504.   (if (= n 0)
  2505.       a
  2506.     (if (consp a)
  2507.     (cons (car a) (math-scale-left-bignum (cdr a) n))
  2508.       (if (>= n 3)
  2509.       (if (or (>= a 1000) (<= a -1000))
  2510.           (math-scale-left (math-bignum a) n)
  2511.         (math-scale-left (* a 1000) (- n 3)))
  2512.     (if (= n 2)
  2513.         (if (or (>= a 10000) (<= a -10000))
  2514.         (math-scale-left (math-bignum a) 2)
  2515.           (* a 100))
  2516.       (if (or (>= a 100000) (<= a -100000))
  2517.           (math-scale-left (math-bignum a) 1)
  2518.         (* a 10))))))
  2519. )
  2520.  
  2521. (defun math-scale-left-bignum (a n)
  2522.   (if (>= n 3)
  2523.       (while (>= (setq a (cons 0 a)
  2524.                n (- n 3)) 3)))
  2525.   (if (> n 0)
  2526.       (math-mul-bignum-digit a (if (= n 2) 100 10) 0)
  2527.     a)
  2528. )
  2529.  
  2530. (defun math-scale-right (a n)   ; [i i S]
  2531.   (if (= n 0)
  2532.       a
  2533.     (if (consp a)
  2534.     (cons (car a) (math-scale-right-bignum (cdr a) n))
  2535.       (if (<= a 0)
  2536.       (if (= a 0)
  2537.           0
  2538.         (- (math-scale-right (- a) n)))
  2539.     (if (>= n 3)
  2540.         (while (and (> (setq a (/ a 1000)) 0)
  2541.             (>= (setq n (- n 3)) 3))))
  2542.     (if (= n 2)
  2543.         (/ a 100)
  2544.       (if (= n 1)
  2545.           (/ a 10)
  2546.         a)))))
  2547. )
  2548.  
  2549. (defun math-scale-right-bignum (a n)   ; [L L S; l l S]
  2550.   (if (>= n 3)
  2551.       (setq a (nthcdr (/ n 3) a)
  2552.         n (% n 3)))
  2553.   (if (> n 0)
  2554.       (cdr (math-mul-bignum-digit a (if (= n 2) 10 100) 0))
  2555.     a)
  2556. )
  2557.  
  2558. ;;; Multiply (with rounding) the integer A by 10^N.   [I i S]
  2559. (defun math-scale-rounding (a n)
  2560.   (cond ((>= n 0)
  2561.      (math-scale-left a n))
  2562.     ((consp a)
  2563.      (math-normalize
  2564.       (cons (car a)
  2565.         (let ((val (if (< n -3)
  2566.                    (math-scale-right-bignum (cdr a) (- -3 n))
  2567.                  (if (= n -2)
  2568.                  (math-mul-bignum-digit (cdr a) 10 0)
  2569.                    (if (= n -1)
  2570.                    (math-mul-bignum-digit (cdr a) 100 0)
  2571.                  (cdr a))))))  ; n = -3
  2572.           (if (and val (>= (car val) 500))
  2573.               (if (cdr val)
  2574.               (if (eq (car (cdr val)) 999)
  2575.                   (math-add-bignum (cdr val) '(1))
  2576.                 (cons (1+ (car (cdr val))) (cdr (cdr val))))
  2577.             '(1))
  2578.             (cdr val))))))
  2579.     (t
  2580.      (if (< a 0)
  2581.          (- (math-scale-rounding (- a) n))
  2582.        (if (= n -1)
  2583.            (/ (+ a 5) 10)
  2584.          (/ (+ (math-scale-right a (- -1 n)) 5) 10)))))
  2585. )
  2586.  
  2587.  
  2588. ;;; Compute the sum of A and B.  [O O O] [Public]
  2589. (defun math-add (a b)
  2590.   (or
  2591.    (and (not (or (consp a) (consp b)))
  2592.     (progn
  2593.       (setq a (+ a b))
  2594.       (if (or (<= a -1000000) (>= a 1000000))
  2595.           (math-bignum a)
  2596.         a)))
  2597.    (and (Math-zerop a) (not (eq (car-safe a) 'mod))
  2598.     (if (and (math-floatp a) (Math-ratp b)) (math-float b) b))
  2599.    (and (Math-zerop b) (not (eq (car-safe b) 'mod))
  2600.     (if (and (math-floatp b) (Math-ratp a)) (math-float a) a))
  2601.    (and (Math-objvecp a) (Math-objvecp b)
  2602.     (or
  2603.      (and (Math-integerp a) (Math-integerp b)
  2604.           (progn
  2605.         (or (consp a) (setq a (math-bignum a)))
  2606.         (or (consp b) (setq b (math-bignum b)))
  2607.         (if (eq (car a) 'bigneg)
  2608.             (if (eq (car b) 'bigneg)
  2609.             (cons 'bigneg (math-add-bignum (cdr a) (cdr b)))
  2610.               (math-normalize
  2611.                (let ((diff (math-sub-bignum (cdr b) (cdr a))))
  2612.              (if (eq diff 'neg)
  2613.                  (cons 'bigneg (math-sub-bignum (cdr a) (cdr b)))
  2614.                (cons 'bigpos diff)))))
  2615.           (if (eq (car b) 'bigneg)
  2616.               (math-normalize
  2617.                (let ((diff (math-sub-bignum (cdr a) (cdr b))))
  2618.              (if (eq diff 'neg)
  2619.                  (cons 'bigneg (math-sub-bignum (cdr b) (cdr a)))
  2620.                (cons 'bigpos diff))))
  2621.             (cons 'bigpos (math-add-bignum (cdr a) (cdr b)))))))
  2622.      (and (Math-ratp a) (Math-ratp b)
  2623.           (calc-extensions)
  2624.           (calc-add-fractions a b))
  2625.      (and (Math-realp a) (Math-realp b)
  2626.           (progn
  2627.         (or (and (consp a) (eq (car a) 'float))
  2628.             (setq a (math-float a)))
  2629.         (or (and (consp b) (eq (car b) 'float))
  2630.             (setq b (math-float b)))
  2631.         (math-add-float a b)))
  2632.      (and (calc-extensions)
  2633.           (math-add-objects-fancy a b))))
  2634.    (and (calc-extensions)
  2635.     (math-add-symb-fancy a b)))
  2636. )
  2637.  
  2638. (defun math-add-bignum (a b)   ; [L L L; l l l]
  2639.   (if a
  2640.       (if b
  2641.       (let* ((a (copy-sequence a)) (aa a) (carry nil) sum)
  2642.         (while (and aa b)
  2643.           (if carry
  2644.           (if (< (setq sum (+ (car aa) (car b))) 999)
  2645.               (progn
  2646.             (setcar aa (1+ sum))
  2647.             (setq carry nil))
  2648.             (setcar aa (+ sum -999)))
  2649.         (if (< (setq sum (+ (car aa) (car b))) 1000)
  2650.             (setcar aa sum)
  2651.           (setcar aa (+ sum -1000))
  2652.           (setq carry t)))
  2653.           (setq aa (cdr aa)
  2654.             b (cdr b)))
  2655.         (if carry
  2656.         (if b
  2657.             (nconc a (math-add-bignum b '(1)))
  2658.           (while (eq (car aa) 999)
  2659.             (setcar aa 0)
  2660.             (setq aa (cdr aa)))
  2661.           (if aa
  2662.               (progn
  2663.             (setcar aa (1+ (car aa)))
  2664.             a)
  2665.             (nconc a '(1))))
  2666.           (if b
  2667.           (nconc a b)
  2668.         a)))
  2669.     a)
  2670.     b)
  2671. )
  2672.  
  2673. (defun math-sub-bignum (a b)   ; [l l l]
  2674.   (if b
  2675.       (if a
  2676.       (let* ((a (copy-sequence a)) (aa a) (borrow nil) sum)
  2677.         (while (and aa b)
  2678.           (if borrow
  2679.           (if (>= (setq diff (- (car aa) (car b))) 1)
  2680.               (progn
  2681.             (setcar aa (1- diff))
  2682.             (setq borrow nil))
  2683.             (setcar aa (+ diff 999)))
  2684.         (if (>= (setq diff (- (car aa) (car b))) 0)
  2685.             (setcar aa diff)
  2686.           (setcar aa (+ diff 1000))
  2687.           (setq borrow t)))
  2688.           (setq aa (cdr aa)
  2689.             b (cdr b)))
  2690.         (if borrow
  2691.         (progn
  2692.           (while (eq (car aa) 0)
  2693.             (setcar aa 999)
  2694.             (setq aa (cdr aa)))
  2695.           (if aa
  2696.               (progn
  2697.             (setcar aa (1- (car aa)))
  2698.             a)
  2699.             'neg))
  2700.           (while (eq (car b) 0)
  2701.         (setq b (cdr b)))
  2702.           (if b
  2703.           'neg
  2704.         a)))
  2705.     (while (eq (car b) 0)
  2706.       (setq b (cdr b)))
  2707.     (and b
  2708.          'neg))
  2709.     a)
  2710. )
  2711.  
  2712. (defun math-add-float (a b)   ; [F F F]
  2713.   (let ((ediff (- (nth 2 a) (nth 2 b))))
  2714.     (if (>= ediff 0)
  2715.     (if (>= ediff (+ calc-internal-prec calc-internal-prec))
  2716.         a
  2717.       (math-make-float (math-add (nth 1 b)
  2718.                      (if (eq ediff 0)
  2719.                      (nth 1 a)
  2720.                        (math-scale-left (nth 1 a) ediff)))
  2721.                (nth 2 b)))
  2722.       (if (>= (setq ediff (- ediff))
  2723.           (+ calc-internal-prec calc-internal-prec))
  2724.       b
  2725.     (math-make-float (math-add (nth 1 a)
  2726.                    (math-scale-left (nth 1 b) ediff))
  2727.              (nth 2 a)))))
  2728. )
  2729.  
  2730. ;;; Compute the difference of A and B.  [O O O] [Public]
  2731. (defun math-sub (a b)
  2732.   (if (or (consp a) (consp b))
  2733.       (math-add a (math-neg b))
  2734.     (setq a (- a b))
  2735.     (if (or (<= a -1000000) (>= a 1000000))
  2736.     (math-bignum a)
  2737.       a))
  2738. )
  2739.  
  2740. (defun math-sub-float (a b)   ; [F F F]
  2741.   (let ((ediff (- (nth 2 a) (nth 2 b))))
  2742.     (if (>= ediff 0)
  2743.     (if (>= ediff (+ calc-internal-prec calc-internal-prec))
  2744.         a
  2745.       (math-make-float (math-add (Math-integer-neg (nth 1 b))
  2746.                      (if (eq ediff 0)
  2747.                      (nth 1 a)
  2748.                        (math-scale-left (nth 1 a) ediff)))
  2749.                (nth 2 b)))
  2750.       (if (>= (setq ediff (- ediff))
  2751.           (+ calc-internal-prec calc-internal-prec))
  2752.       b
  2753.     (math-make-float (math-add (nth 1 a)
  2754.                    (Math-integer-neg
  2755.                     (math-scale-left (nth 1 b) ediff)))
  2756.              (nth 2 a)))))
  2757. )
  2758.  
  2759.  
  2760. ;;; Compute the product of A and B.  [O O O] [Public]
  2761. (defun math-mul (a b)
  2762.   (or
  2763.    (and (not (consp a)) (not (consp b))
  2764.     (< a 1000) (> a -1000) (< b 1000) (> b -1000)
  2765.     (* a b))
  2766.    (and (Math-zerop a) (not (eq (car-safe b) 'mod))
  2767.     (if (Math-scalarp b)
  2768.         (if (and (math-floatp b) (Math-ratp a)) (math-float a) a)
  2769.       (calc-extensions)
  2770.       (math-mul-zero a b)))
  2771.    (and (Math-zerop b) (not (eq (car-safe a) 'mod))
  2772.     (if (Math-scalarp a)
  2773.         (if (and (math-floatp a) (Math-ratp b)) (math-float b) b)
  2774.       (calc-extensions)
  2775.       (math-mul-zero b a)))
  2776.    (and (Math-objvecp a) (Math-objvecp b)
  2777.     (or
  2778.      (and (Math-integerp a) (Math-integerp b)
  2779.           (progn
  2780.         (or (consp a) (setq a (math-bignum a)))
  2781.         (or (consp b) (setq b (math-bignum b)))
  2782.         (math-normalize
  2783.          (cons (if (eq (car a) (car b)) 'bigpos 'bigneg)
  2784.                (if (cdr (cdr a))
  2785.                (if (cdr (cdr b))
  2786.                    (math-mul-bignum (cdr a) (cdr b))
  2787.                  (math-mul-bignum-digit (cdr a) (nth 1 b) 0))
  2788.              (math-mul-bignum-digit (cdr b) (nth 1 a) 0))))))
  2789.      (and (Math-ratp a) (Math-ratp b)
  2790.           (calc-extensions)
  2791.           (calc-mul-fractions a b))
  2792.      (and (Math-realp a) (Math-realp b)
  2793.           (progn
  2794.         (or (and (consp a) (eq (car a) 'float))
  2795.             (setq a (math-float a)))
  2796.         (or (and (consp b) (eq (car b) 'float))
  2797.             (setq b (math-float b)))
  2798.         (math-make-float (math-mul (nth 1 a) (nth 1 b))
  2799.                  (+ (nth 2 a) (nth 2 b)))))
  2800.      (and (calc-extensions)
  2801.           (math-mul-objects-fancy a b))))
  2802.    (and (calc-extensions)
  2803.     (math-mul-symb-fancy a b)))
  2804. )
  2805.  
  2806. (defun math-infinitep (a &optional undir)
  2807.   (while (and (consp a) (memq (car a) '(* / neg)))
  2808.     (if (or (not (eq (car a) '*)) (math-infinitep (nth 1 a)))
  2809.     (setq a (nth 1 a))
  2810.       (setq a (nth 2 a))))
  2811.   (and (consp a)
  2812.        (eq (car a) 'var)
  2813.        (memq (nth 2 a) '(var-inf var-uinf var-nan))
  2814.        (if (and undir (eq (nth 2 a) 'var-inf))
  2815.        '(var uinf var-uinf)
  2816.      a))
  2817. )
  2818.  
  2819. ;;; Multiply digit lists A and B.  [L L L; l l l]
  2820. (defun math-mul-bignum (a b)
  2821.   (and a b
  2822.        (let* ((sum (if (<= (car b) 1)
  2823.                (if (= (car b) 0)
  2824.                (list 0)
  2825.              (copy-sequence a))
  2826.              (math-mul-bignum-digit a (car b) 0)))
  2827.           (sump sum) c d aa ss prod)
  2828.      (while (setq b (cdr b))
  2829.        (setq ss (setq sump (or (cdr sump) (setcdr sump (list 0))))
  2830.          d (car b)
  2831.          c 0
  2832.          aa a)
  2833.        (while (progn
  2834.             (setcar ss (% (setq prod (+ (+ (car ss) (* (car aa) d))
  2835.                         c)) 1000))
  2836.             (setq aa (cdr aa)))
  2837.          (setq c (/ prod 1000)
  2838.            ss (or (cdr ss) (setcdr ss (list 0)))))
  2839.        (if (>= prod 1000)
  2840.            (if (cdr ss)
  2841.            (setcar (cdr ss) (+ (/ prod 1000) (car (cdr ss))))
  2842.          (setcdr ss (list (/ prod 1000))))))
  2843.      sum))
  2844. )
  2845.  
  2846. ;;; Multiply digit list A by digit D.  [L L D D; l l D D]
  2847. (defun math-mul-bignum-digit (a d c)
  2848.   (if a
  2849.       (if (<= d 1)
  2850.       (and (= d 1) a)
  2851.     (let* ((a (copy-sequence a)) (aa a) prod)
  2852.       (while (progn
  2853.            (setcar aa (% (setq prod (+ (* (car aa) d) c)) 1000))
  2854.            (cdr aa))
  2855.         (setq aa (cdr aa)
  2856.           c (/ prod 1000)))
  2857.       (if (>= prod 1000)
  2858.           (setcdr aa (list (/ prod 1000))))
  2859.       a))
  2860.     (and (> c 0)
  2861.      (list c)))
  2862. )
  2863.  
  2864.  
  2865. ;;; Compute the integer (quotient . remainder) of A and B, which may be
  2866. ;;; small or big integers.  Type and consistency of truncation is undefined
  2867. ;;; if A or B is negative.  B must be nonzero.  [I.I I I] [Public]
  2868. (defun math-idivmod (a b)
  2869.   (if (eq b 0)
  2870.       (math-reject-arg a "*Division by zero"))
  2871.   (if (or (consp a) (consp b))
  2872.       (if (and (natnump b) (< b 1000))
  2873.       (let ((res (math-div-bignum-digit (cdr a) b)))
  2874.         (cons
  2875.          (math-normalize (cons (car a) (car res)))
  2876.          (cdr res)))
  2877.     (or (consp a) (setq a (math-bignum a)))
  2878.     (or (consp b) (setq b (math-bignum b)))
  2879.     (let ((res (math-div-bignum (cdr a) (cdr b))))
  2880.       (cons
  2881.        (math-normalize (cons (if (eq (car a) (car b)) 'bigpos 'bigneg)
  2882.                  (car res)))
  2883.        (math-normalize (cons (car a) (cdr res))))))
  2884.     (cons (/ a b) (% a b)))
  2885. )
  2886.  
  2887. (defun math-quotient (a b)   ; [I I I] [Public]
  2888.   (if (and (not (consp a)) (not (consp b)))
  2889.       (if (= b 0)
  2890.       (math-reject-arg a "*Division by zero")
  2891.     (/ a b))
  2892.     (if (and (natnump b) (< b 1000))
  2893.     (if (= b 0)
  2894.         (math-reject-arg a "*Division by zero")
  2895.       (math-normalize (cons (car a)
  2896.                 (car (math-div-bignum-digit (cdr a) b)))))
  2897.       (or (consp a) (setq a (math-bignum a)))
  2898.       (or (consp b) (setq b (math-bignum b)))
  2899.       (let* ((alen (1- (length a)))
  2900.          (blen (1- (length b)))
  2901.          (d (/ 1000 (1+ (nth (1- blen) (cdr b)))))
  2902.          (res (math-div-bignum-big (math-mul-bignum-digit (cdr a) d 0)
  2903.                        (math-mul-bignum-digit (cdr b) d 0)
  2904.                        alen blen)))
  2905.     (math-normalize (cons (if (eq (car a) (car b)) 'bigpos 'bigneg)
  2906.                   (car res))))))
  2907. )
  2908.  
  2909.  
  2910. ;;; Divide a bignum digit list by another.  [l.l l L]
  2911. ;;; The following division algorithm is borrowed from Knuth vol. II, sec. 4.3.1
  2912. (defun math-div-bignum (a b)
  2913.   (if (cdr b)
  2914.       (let* ((alen (length a))
  2915.          (blen (length b))
  2916.          (d (/ 1000 (1+ (nth (1- blen) b))))
  2917.          (res (math-div-bignum-big (math-mul-bignum-digit a d 0)
  2918.                        (math-mul-bignum-digit b d 0)
  2919.                        alen blen)))
  2920.     (if (= d 1)
  2921.         res
  2922.       (cons (car res)
  2923.         (car (math-div-bignum-digit (cdr res) d)))))
  2924.     (let ((res (math-div-bignum-digit a (car b))))
  2925.       (cons (car res) (list (cdr res)))))
  2926. )
  2927.  
  2928. ;;; Divide a bignum digit list by a digit.  [l.D l D]
  2929. (defun math-div-bignum-digit (a b)
  2930.   (if a
  2931.       (let* ((res (math-div-bignum-digit (cdr a) b))
  2932.          (num (+ (* (cdr res) 1000) (car a))))
  2933.     (cons
  2934.      (cons (/ num b) (car res))
  2935.      (% num b)))
  2936.     '(nil . 0))
  2937. )
  2938.  
  2939. (defun math-div-bignum-big (a b alen blen)   ; [l.l l L]
  2940.   (if (< alen blen)
  2941.       (cons nil a)
  2942.     (let* ((res (math-div-bignum-big (cdr a) b (1- alen) blen))
  2943.        (num (cons (car a) (cdr res)))
  2944.        (res2 (math-div-bignum-part num b blen)))
  2945.       (cons
  2946.        (cons (car res2) (car res))
  2947.        (cdr res2))))
  2948. )
  2949.  
  2950. (defun math-div-bignum-part (a b blen)   ; a < b*1000  [D.l l L]
  2951.   (let* ((num (+ (* (or (nth blen a) 0) 1000) (or (nth (1- blen) a) 0)))
  2952.      (den (nth (1- blen) b))
  2953.      (guess (min (/ num den) 999)))
  2954.     (math-div-bignum-try a b (math-mul-bignum-digit b guess 0) guess))
  2955. )
  2956.  
  2957. (defun math-div-bignum-try (a b c guess)   ; [D.l l l D]
  2958.   (let ((rem (math-sub-bignum a c)))
  2959.     (if (eq rem 'neg)
  2960.     (math-div-bignum-try a b (math-sub-bignum c b) (1- guess))
  2961.       (cons guess rem)))
  2962. )
  2963.  
  2964.  
  2965. ;;; Compute the quotient of A and B.  [O O N] [Public]
  2966. (defun math-div (a b)
  2967.   (or
  2968.    (and (Math-zerop b)
  2969.     (calc-extensions)
  2970.     (math-div-by-zero a b))
  2971.    (and (Math-zerop a) (not (eq (car-safe b) 'mod))
  2972.     (if (Math-scalarp b)
  2973.         (if (and (math-floatp b) (Math-ratp a)) (math-float a) a)
  2974.       (calc-extensions)
  2975.       (math-div-zero a b)))
  2976.    (and (Math-objvecp a) (Math-objvecp b)
  2977.     (or
  2978.      (and (Math-integerp a) (Math-integerp b)
  2979.           (let ((q (math-idivmod a b)))
  2980.         (if (eq (cdr q) 0)
  2981.             (car q)
  2982.           (if calc-prefer-frac
  2983.               (progn
  2984.             (calc-extensions)
  2985.             (math-make-frac a b))
  2986.             (math-div-float (math-make-float a 0)
  2987.                     (math-make-float b 0))))))
  2988.      (and (Math-ratp a) (Math-ratp b)
  2989.           (calc-extensions)
  2990.           (calc-div-fractions a b))
  2991.      (and (Math-realp a) (Math-realp b)
  2992.           (progn
  2993.         (or (and (consp a) (eq (car a) 'float))
  2994.             (setq a (math-float a)))
  2995.         (or (and (consp b) (eq (car b) 'float))
  2996.             (setq b (math-float b)))
  2997.         (math-div-float a b)))
  2998.      (and (calc-extensions)
  2999.           (math-div-objects-fancy a b))))
  3000.    (and (calc-extensions)
  3001.     (math-div-symb-fancy a b)))
  3002. )
  3003.  
  3004. (defun math-div-float (a b)   ; [F F F]
  3005.   (let ((ldiff (max (- (1+ calc-internal-prec)
  3006.                (- (math-numdigs (nth 1 a)) (math-numdigs (nth 1 b))))
  3007.             0)))
  3008.     (math-make-float (math-quotient (math-scale-int (nth 1 a) ldiff) (nth 1 b))
  3009.              (- (- (nth 2 a) (nth 2 b)) ldiff)))
  3010. )
  3011.  
  3012.  
  3013.  
  3014.  
  3015.  
  3016. ;;; Format the number A as a string.  [X N; X Z] [Public]
  3017. (defun math-format-stack-value (entry)
  3018.   (setq calc-selection-cache-entry calc-selection-cache-default-entry)
  3019.   (let* ((a (car entry))
  3020.      (math-comp-selected (nth 2 entry))
  3021.      (c (cond ((null a) "<nil>")
  3022.           ((eq calc-display-raw t) (format "%s" a))
  3023.           ((stringp a) a)
  3024.           ((eq a 'top-of-stack) ".")
  3025.           (calc-prepared-composition
  3026.            calc-prepared-composition)
  3027.           ((and (Math-scalarp a)
  3028.             (memq calc-language '(nil flat unform))
  3029.             (null math-comp-selected))
  3030.            (math-format-number a))
  3031.           (t (calc-extensions)
  3032.              (math-compose-expr a 0))))
  3033.      (off (math-stack-value-offset c))
  3034.      s w)
  3035.     (and math-comp-selected (setq calc-any-selections t))
  3036.     (setq w (cdr off)
  3037.       off (car off))
  3038.     (if (> off 0)
  3039.     (setq c (math-comp-concat (make-string off ? ) c)))
  3040.     (or (equal calc-left-label "")
  3041.     (setq c (math-comp-concat (if (eq a 'top-of-stack)
  3042.                       (make-string (length calc-left-label) ? )
  3043.                     calc-left-label)
  3044.                   c)))
  3045.     (if calc-line-numbering
  3046.     (setq c (math-comp-concat (if (eq calc-language 'big)
  3047.                       (if math-comp-selected
  3048.                       '(tag t "1:  ") "1:  ")
  3049.                     "    ")
  3050.                   c)))
  3051.     (or (equal calc-right-label "")
  3052.     (eq a 'top-of-stack)
  3053.     (progn
  3054.       (calc-extensions)
  3055.       (setq c (list 'horiz c
  3056.             (make-string (max (- w (math-comp-width c)
  3057.                          (length calc-right-label)) 0) ? )
  3058.             '(break -1)
  3059.             calc-right-label))))
  3060.     (setq s (if (stringp c)
  3061.         (if calc-display-raw
  3062.             (prin1-to-string c)
  3063.           c)
  3064.           (math-composition-to-string c w)))
  3065.     (if calc-language-output-filter
  3066.     (setq s (funcall calc-language-output-filter s)))
  3067.     (if (eq calc-language 'big)
  3068.     (setq s (concat s "\n"))
  3069.       (if calc-line-numbering
  3070.       (progn
  3071.         (aset s 0 ?1)
  3072.         (aset s 1 ?:))))
  3073.     (setcar (cdr entry) (calc-count-lines s))
  3074.     s)
  3075. )
  3076.  
  3077. (defun math-stack-value-offset (c)
  3078.   (let* ((num (if calc-line-numbering 4 0))
  3079.      (wid (calc-window-width))
  3080.      off)
  3081.     (if calc-display-just
  3082.     (progn
  3083.       (calc-extensions)
  3084.       (math-stack-value-offset-fancy))
  3085.       (setq off (or calc-display-origin 0))
  3086.       (if (integerp calc-line-breaking)
  3087.       (setq wid calc-line-breaking)))
  3088.     (cons (max (- off (length calc-left-label)) 0)
  3089.       (+ wid num)))
  3090. )
  3091.  
  3092. (defun calc-count-lines (s)
  3093.   (let ((pos 0)
  3094.     (num 1))
  3095.     (while (setq newpos (string-match "\n" s pos))
  3096.       (setq pos (1+ newpos)
  3097.         num (1+ num)))
  3098.     num)
  3099. )
  3100.  
  3101. (defun math-format-value (a &optional w)
  3102.   (if (and (Math-scalarp a)
  3103.        (memq calc-language '(nil flat unform)))
  3104.       (math-format-number a)
  3105.     (calc-extensions)
  3106.     (let ((calc-line-breaking nil))
  3107.       (math-composition-to-string (math-compose-expr a 0) w)))
  3108. )
  3109.  
  3110. (defun calc-window-width ()
  3111.   (if calc-embedded-info
  3112.       (let ((win (get-buffer-window (aref calc-embedded-info 0))))
  3113.     (1- (if win (window-width win) (screen-width))))
  3114.     (- (window-width (get-buffer-window (current-buffer)))
  3115.        (if calc-line-numbering 5 1)))
  3116. )
  3117.  
  3118. (defun math-comp-concat (c1 c2)
  3119.   (if (and (stringp c1) (stringp c2))
  3120.       (concat c1 c2)
  3121.     (list 'horiz c1 c2))
  3122. )
  3123.  
  3124.  
  3125.  
  3126. ;;; Format an expression as a one-line string suitable for re-reading.
  3127.  
  3128. (defun math-format-flat-expr (a prec)
  3129.   (cond
  3130.    ((or (not (or (consp a) (integerp a)))
  3131.     (eq calc-display-raw t))
  3132.     (let ((print-escape-newlines t))
  3133.       (concat "'" (prin1-to-string a))))
  3134.    ((Math-scalarp a)
  3135.     (let ((calc-group-digits nil)
  3136.       (calc-point-char ".")
  3137.       (calc-frac-format (if (> (length (car calc-frac-format)) 1)
  3138.                 '("::" nil) '(":" nil)))
  3139.       (calc-complex-format nil)
  3140.       (calc-hms-format "%s@ %s' %s\"")
  3141.       (calc-language nil))
  3142.       (math-format-number a)))
  3143.    (t
  3144.     (calc-extensions)
  3145.     (math-format-flat-expr-fancy a prec)))
  3146. )
  3147.  
  3148.  
  3149.  
  3150. ;;; Format a number as a string.
  3151. (defun math-format-number (a &optional prec)   ; [X N]   [Public]
  3152.   (cond
  3153.    ((eq calc-display-raw t) (format "%s" a))
  3154.    ((and (nth 1 calc-frac-format) (Math-integerp a))
  3155.     (calc-extensions)
  3156.     (math-format-number (math-adjust-fraction a)))
  3157.    ((integerp a)
  3158.     (if (not (or calc-group-digits calc-leading-zeros))
  3159.     (if (= calc-number-radix 10)
  3160.         (int-to-string a)
  3161.       (if (< a 0)
  3162.           (concat "-" (math-format-number (- a)))
  3163.         (calc-extensions)
  3164.         (if math-radix-explicit-format
  3165.         (if calc-radix-formatter
  3166.             (funcall calc-radix-formatter
  3167.                  calc-number-radix
  3168.                  (if (= calc-number-radix 2)
  3169.                  (math-format-binary a)
  3170.                    (math-format-radix a)))
  3171.           (format "%d#%s" calc-number-radix
  3172.               (if (= calc-number-radix 2)
  3173.                   (math-format-binary a)
  3174.                 (math-format-radix a))))
  3175.           (math-format-radix a))))
  3176.       (math-format-number (math-bignum a))))
  3177.    ((stringp a) a)
  3178.    ((not (consp a)) (prin1-to-string a))
  3179.    ((eq (car a) 'bigpos) (math-format-bignum (cdr a)))
  3180.    ((eq (car a) 'bigneg) (concat "-" (math-format-bignum (cdr a))))
  3181.    ((and (eq (car a) 'float) (= calc-number-radix 10))
  3182.     (if (Math-integer-negp (nth 1 a))
  3183.     (concat "-" (math-format-number (math-neg a)))
  3184.       (let ((mant (nth 1 a))
  3185.         (exp (nth 2 a))
  3186.         (fmt (car calc-float-format))
  3187.         (figs (nth 1 calc-float-format))
  3188.         (point calc-point-char)
  3189.         str)
  3190.     (if (and (eq fmt 'fix)
  3191.          (or (and (< figs 0) (setq figs (- figs)))
  3192.              (> (+ exp (math-numdigs mant)) (- figs))))
  3193.         (progn
  3194.           (setq mant (math-scale-rounding mant (+ exp figs))
  3195.             str (if (integerp mant)
  3196.                 (int-to-string mant)
  3197.               (math-format-bignum-decimal (cdr mant))))
  3198.           (if (<= (length str) figs)
  3199.           (setq str (concat (make-string (1+ (- figs (length str))) ?0)
  3200.                     str)))
  3201.           (if (> figs 0)
  3202.           (setq str (concat (substring str 0 (- figs)) point
  3203.                     (substring str (- figs))))
  3204.         (setq str (concat str point)))
  3205.           (if calc-group-digits
  3206.           (setq str (math-group-float str))))
  3207.       (if (< figs 0)
  3208.           (setq figs (+ calc-internal-prec figs)))
  3209.       (if (> figs 0)
  3210.           (let ((adj (- figs (math-numdigs mant))))
  3211.         (if (< adj 0)
  3212.             (setq mant (math-scale-rounding mant adj)
  3213.               exp (- exp adj)))))
  3214.       (setq str (if (integerp mant)
  3215.             (int-to-string mant)
  3216.               (math-format-bignum-decimal (cdr mant))))
  3217.       (let* ((len (length str))
  3218.          (dpos (+ exp len)))
  3219.         (if (and (eq fmt 'float)
  3220.              (<= dpos (+ calc-internal-prec calc-display-sci-high))
  3221.              (>= dpos (+ calc-display-sci-low 2)))
  3222.         (progn
  3223.           (cond
  3224.            ((= dpos 0)
  3225.             (setq str (concat "0" point str)))
  3226.            ((and (<= exp 0) (> dpos 0))
  3227.             (setq str (concat (substring str 0 dpos) point
  3228.                       (substring str dpos))))
  3229.            ((> exp 0)
  3230.             (setq str (concat str (make-string exp ?0) point)))
  3231.            (t   ; (< dpos 0)
  3232.             (setq str (concat "0" point
  3233.                       (make-string (- dpos) ?0) str))))
  3234.           (if calc-group-digits
  3235.               (setq str (math-group-float str))))
  3236.           (let* ((eadj (+ exp len))
  3237.              (scale (if (eq fmt 'eng)
  3238.                 (1+ (math-mod (+ eadj 300002) 3))
  3239.                   1)))
  3240.         (if (> scale (length str))
  3241.             (setq str (concat str (make-string (- scale (length str))
  3242.                                ?0))))
  3243.         (if (< scale (length str))
  3244.             (setq str (concat (substring str 0 scale) point
  3245.                       (substring str scale))))
  3246.         (if calc-group-digits
  3247.             (setq str (math-group-float str)))
  3248.         (setq str (format (if (memq calc-language '(math maple))
  3249.                       (if (and prec (> prec 191))
  3250.                       "(%s*10.^%d)" "%s*10.^%d")
  3251.                     "%se%d")
  3252.                   str (- eadj scale)))))))
  3253.     str)))
  3254.    (t
  3255.     (calc-extensions)
  3256.     (math-format-number-fancy a prec)))
  3257. )
  3258.  
  3259. (defun math-format-bignum (a)   ; [X L]
  3260.   (if (and (= calc-number-radix 10)
  3261.        (not calc-leading-zeros)
  3262.        (not calc-group-digits))
  3263.       (math-format-bignum-decimal a)
  3264.     (calc-extensions)
  3265.     (math-format-bignum-fancy a))
  3266. )
  3267.  
  3268. (defun math-format-bignum-decimal (a)   ; [X L]
  3269.   (if a
  3270.       (let ((s ""))
  3271.     (while (cdr (cdr a))
  3272.       (setq s (concat (format "%06d" (+ (* (nth 1 a) 1000) (car a))) s)
  3273.         a (cdr (cdr a))))
  3274.     (concat (int-to-string (+ (* (or (nth 1 a) 0) 1000) (car a))) s))
  3275.     "0")
  3276. )
  3277.  
  3278.  
  3279.  
  3280. ;;; Parse a simple number in string form.   [N X] [Public]
  3281. (defun math-read-number (s)
  3282.   (math-normalize
  3283.    (cond
  3284.  
  3285.     ;; Integers (most common case)
  3286.     ((string-match "\\` *\\([0-9]+\\) *\\'" s)
  3287.      (let ((digs (math-match-substring s 1)))
  3288.        (if (and (eq calc-language 'c)
  3289.         (> (length digs) 1)
  3290.         (eq (aref digs 0) ?0))
  3291.        (math-read-number (concat "8#" digs))
  3292.      (if (<= (length digs) 6)
  3293.          (string-to-int digs)
  3294.        (cons 'bigpos (math-read-bignum digs))))))
  3295.  
  3296.     ;; Clean up the string if necessary
  3297.     ((string-match "\\`\\(.*\\)[ \t\n]+\\([^\001]\\)*\\'" s)
  3298.      (math-read-number (concat (math-match-substring s 1)
  3299.                    (math-match-substring s 2))))
  3300.  
  3301.     ;; Plus and minus signs
  3302.     ((string-match "^[-_+]\\(.*\\)$" s)
  3303.      (let ((val (math-read-number (math-match-substring s 1))))
  3304.        (and val (if (eq (aref s 0) ?+) val (math-neg val)))))
  3305.  
  3306.     ;; Forms that require extensions module
  3307.     ((string-match "[^-+0-9eE.]" s)
  3308.      (calc-extensions)
  3309.      (math-read-number-fancy s))
  3310.  
  3311.     ;; Decimal point
  3312.     ((string-match "^\\([0-9]*\\)\\.\\([0-9]*\\)$" s)
  3313.      (let ((int (math-match-substring s 1))
  3314.        (frac (math-match-substring s 2)))
  3315.        (let ((ilen (length int))
  3316.          (flen (length frac)))
  3317.      (let ((int (if (> ilen 0) (math-read-number int) 0))
  3318.            (frac (if (> flen 0) (math-read-number frac) 0)))
  3319.        (and int frac (or (> ilen 0) (> flen 0))
  3320.         (list 'float
  3321.               (math-add (math-scale-int int flen) frac)
  3322.               (- flen)))))))
  3323.  
  3324.     ;; "e" notation
  3325.     ((string-match "^\\(.*\\)[eE]\\([-+]?[0-9]+\\)$" s)
  3326.      (let ((mant (math-match-substring s 1))
  3327.        (exp (math-match-substring s 2)))
  3328.        (let ((mant (if (> (length mant) 0) (math-read-number mant) 1))
  3329.          (exp (if (<= (length exp) (if (memq (aref exp 0) '(?+ ?-)) 8 7))
  3330.               (string-to-int exp))))
  3331.      (and mant exp (Math-realp mant) (> exp -4000000) (< exp 4000000)
  3332.           (let ((mant (math-float mant)))
  3333.         (list 'float (nth 1 mant) (+ (nth 2 mant) exp)))))))
  3334.  
  3335.     ;; Syntax error!
  3336.     (t nil)))
  3337. )
  3338.  
  3339. (defun math-match-substring (s n)
  3340.   (if (match-beginning n)
  3341.       (substring s (match-beginning n) (match-end n))
  3342.     "")
  3343. )
  3344.  
  3345. (defun math-read-bignum (s)   ; [l X]
  3346.   (if (> (length s) 3)
  3347.       (cons (string-to-int (substring s -3))
  3348.         (math-read-bignum (substring s 0 -3)))
  3349.     (list (string-to-int s)))
  3350. )
  3351.  
  3352.  
  3353. (defconst math-tex-ignore-words
  3354.   '( ("\\hbox") ("\\mbox") ("\\text") ("\\left") ("\\right")
  3355.      ("\\,") ("\\>") ("\\:") ("\\;") ("\\!") ("\\ ")
  3356.      ("\\quad") ("\\qquad") ("\\hfil") ("\\hfill")
  3357.      ("\\displaystyle") ("\\textstyle") ("\\dsize") ("\\tsize")
  3358.      ("\\scriptstyle") ("\\scriptscriptstyle") ("\\ssize") ("\\sssize")
  3359.      ("\\rm") ("\\bf") ("\\it") ("\\sl")
  3360.      ("\\roman") ("\\bold") ("\\italic") ("\\slanted")
  3361.      ("\\cal") ("\\mit") ("\\Cal") ("\\Bbb") ("\\frak") ("\\goth")
  3362.      ("\\evalto")
  3363.      ("\\matrix" mat) ("\\bmatrix" mat) ("\\pmatrix" mat)
  3364.      ("\\cr" punc ";") ("\\\\" punc ";") ("\\*" punc "*")
  3365.      ("\\{" punc "[") ("\\}" punc "]")
  3366. ))
  3367.  
  3368. (defconst math-eqn-ignore-words
  3369.   '( ("roman") ("bold") ("italic") ("mark") ("lineup") ("evalto")
  3370.      ("left" ("floor") ("ceil"))
  3371.      ("right" ("floor") ("ceil"))
  3372.      ("arc" ("sin") ("cos") ("tan") ("sinh") ("cosh") ("tanh"))
  3373.      ("size" n) ("font" n) ("fwd" n) ("back" n) ("up" n) ("down" n)
  3374.      ("above" punc ",")
  3375. ))
  3376.  
  3377. (defconst math-standard-opers
  3378.   '( ( "_"     calcFunc-subscr 1200 1201 )
  3379.      ( "%"     calcFunc-percent 1100 -1 )
  3380.      ( "u+"    ident         -1 1000 )
  3381.      ( "u-"    neg         -1 1000 197 )
  3382.      ( "u!"    calcFunc-lnot -1 1000 )
  3383.      ( "mod"   mod         400 400 185 )
  3384.      ( "+/-"   sdev         300 300 185 )
  3385.      ( "!!"    calcFunc-dfact 210 -1 )
  3386.      ( "!"     calcFunc-fact 210  -1 )
  3387.      ( "^"     ^             201 200 )
  3388.      ( "**"    ^             201 200 )
  3389.      ( "*"     *             196 195 )
  3390.      ( "2x"    *             196 195 )
  3391.      ( "/"     /             190 191 )
  3392.      ( "%"     %             190 191 )
  3393.      ( "\\"    calcFunc-idiv 190 191 )
  3394.      ( "+"     +         180 181 )
  3395.      ( "-"     -         180 181 )
  3396.      ( "|"     |         170 171 )
  3397.      ( "<"     calcFunc-lt   160 161 )
  3398.      ( ">"     calcFunc-gt   160 161 )
  3399.      ( "<="    calcFunc-leq  160 161 )
  3400.      ( ">="    calcFunc-geq  160 161 )
  3401.      ( "="     calcFunc-eq   160 161 )
  3402.      ( "=="    calcFunc-eq   160 161 )
  3403.      ( "!="    calcFunc-neq  160 161 )
  3404.      ( "&&"    calcFunc-land 110 111 )
  3405.      ( "||"    calcFunc-lor  100 101 )
  3406.      ( "?"     (math-read-if) 91  90 )
  3407.      ( "!!!"   calcFunc-pnot  -1  85 )
  3408.      ( "&&&"   calcFunc-pand  80  81 )
  3409.      ( "|||"   calcFunc-por   75  76 )
  3410.      ( ":="    calcFunc-assign 51 50 )
  3411.      ( "::"    calcFunc-condition 45 46 )
  3412.      ( "=>"    calcFunc-evalto 40 41 )
  3413.      ( "=>"    calcFunc-evalto 40 -1 )
  3414. ))
  3415. (setq math-expr-opers math-standard-opers)
  3416.  
  3417.  
  3418. ;;;###autoload
  3419. (defun calc-grab-region (top bot arg)
  3420.   "Parse the region as a vector of numbers and push it on the Calculator stack."
  3421.   (interactive "r\nP")
  3422.   (calc-extensions)
  3423.   (calc-do-grab-region top bot arg)
  3424. )
  3425.  
  3426. ;;;###autoload
  3427. (defun calc-grab-rectangle (top bot arg)
  3428.   "Parse a rectangle as a matrix of numbers and push it on the Calculator stack."
  3429.   (interactive "r\nP")
  3430.   (calc-extensions)
  3431.   (calc-do-grab-rectangle top bot arg)
  3432. )
  3433.  
  3434. (defun calc-grab-sum-down (top bot arg)
  3435.   "Parse a rectangle as a matrix of numbers and sum its columns."
  3436.   (interactive "r\nP")
  3437.   (calc-extensions)
  3438.   (calc-do-grab-rectangle top bot arg 'calcFunc-reduced)
  3439. )
  3440.  
  3441. (defun calc-grab-sum-across (top bot arg)
  3442.   "Parse a rectangle as a matrix of numbers and sum its rows."
  3443.   (interactive "r\nP")
  3444.   (calc-extensions)
  3445.   (calc-do-grab-rectangle top bot arg 'calcFunc-reducea)
  3446. )
  3447.  
  3448.  
  3449. ;;;###autoload
  3450. (defun calc-embedded (arg &optional end obeg oend)
  3451.   "Start Calc Embedded mode on the formula surrounding point."
  3452.   (interactive "P")
  3453.   (calc-extensions)
  3454.   (calc-do-embedded arg end obeg oend)
  3455. )
  3456.  
  3457. ;;;###autoload
  3458. (defun calc-embedded-activate (&optional arg cbuf)
  3459.   "Scan the current editing buffer for all embedded := and => formulas.
  3460. Also looks for the equivalent TeX words, \\gets and \\evalto."
  3461.   (interactive "P")
  3462.   (calc-do-embedded-activate arg cbuf)
  3463. )
  3464.  
  3465.  
  3466. (defun calc-user-invocation ()
  3467.   (interactive)
  3468.   (or (stringp calc-invocation-macro)
  3469.       (error "Use `Z I' inside Calc to define a `M-# Z' keyboard macro"))
  3470.   (execute-kbd-macro calc-invocation-macro nil)
  3471. )
  3472.  
  3473.  
  3474.  
  3475.  
  3476. ;;; User-programmability.
  3477.  
  3478. ;;;###autoload
  3479. (defmacro defmath (func args &rest body)   ;  [Public]
  3480.   (calc-extensions)
  3481.   (math-do-defmath func args body)
  3482. )
  3483.  
  3484.  
  3485.  
  3486. (if calc-always-load-extensions
  3487.     (progn
  3488.       (calc-extensions)
  3489.       (calc-load-everything))
  3490. )
  3491.  
  3492.  
  3493. (run-hooks 'calc-load-hook)
  3494.  
  3495.  
  3496.